Lesson 3 of 37Thinking in React
Components and Props
Split a UI into function components, pass data with props, children and slots, keep render pure, and reset state with a key.
A real React app is hundreds of small components snapped together: Navbar, Avatar, PriceTag, ProductCard. Being able to look at a design and split it into components, then wire data through them with props, is the first skill every React interview and every code review checks.
A component is a function that returns JSX
A component is a JavaScript function whose name starts with a capital letter and which returns JSX. That is the whole definition.
You use a component like an HTML tag: <Greeting />. React sees the capital letter and calls your function; a lowercase name like <greeting /> would be treated as an unknown HTML tag. Write each component at the top level of the file, never inside another component (a component defined inside another is re-created on every render, which throws away its state).
function card() { ... } and render <card />. What happens?Props: arguments for components
A component that always says the same thing is not very useful. Props (short for properties) are how a parent passes data in. You write them like attributes, and React collects them into one object, the function's first argument.
<PriceTag label="Coffee" cents={350} /> turns into the call PriceTag({ label: "Coffee", cents: 350 }). Strings can use quotes; numbers, booleans, objects, arrays and functions need braces.
Destructuring and defaults
Almost everyone destructures props right in the parameter list. It is shorter, and the signature documents what the component accepts. Default values work exactly like JavaScript default parameters.
A prop written with no value (disabled) means true. The ? in the TypeScript type marks a prop as optional.
What text does this render?
function Badge({ text = "new", count = 1 }) {
return <span>{text} x{count}</span>;
}
<Badge count={3} />Defaults that are objects, and forwarding the rest
A default in the parameter list runs on every render where the prop is missing, not once. For strings and numbers that does not matter. For objects and arrays it does: tags = [] creates a brand-new empty array each time. Usually harmless, but the moment that value reaches a memo comparison or an effect's dependency list, React sees a "different" value on every render and redoes work for nothing. Hoist a shared constant instead:
const NO_TAGS: string[] = [];
function TagList({ tags = NO_TAGS }: { tags?: string[] }) {
return <ul>{tags.map((t) => <li key={t}>{t}</li>)}</ul>;
}Two more facts about defaults. They apply only when the prop is undefined, so a parent that passes null on purpose skips the default. And React 19 removed defaultProps for function components, so parameter defaults are now the only way. You will still see defaultProps in older code and in class components.
Wrapper components often take a few props of their own and pass everything else straight to a DOM element. Collect the leftovers with a rest pattern and spread them back out:
type TextFieldProps = { label: string } & React.ComponentProps<"input">;
function TextField({ label, ...inputProps }: TextFieldProps) {
return (
<label>
{label} <input {...inputProps} />
</label>
);
}
<TextField label="Email" type="email" required autoComplete="email" />;Order matters with spread, because later props win. <input type="text" {...rest} /> lets the caller override type. <input {...rest} type="text" /> forces text no matter what the caller asked for. Decide on purpose which props a caller may override, and merge className by hand instead of letting one silently replace the other.
Which type does the input get, and is it disabled?
function Field(props) {
return <input type="text" {...props} disabled={false} />;
}
<Field type="email" disabled />Children: components that wrap
Anything you put between a component's opening and closing tags arrives as a special prop called children. That is how you build wrappers like cards, modals and layouts that do not care what is inside them.
ReactNode is the TypeScript type for "anything React can render": elements, strings, numbers, arrays, null.
Passing JSX as props: slots
children gives a component one hole to fill. Real components often need several: a page header with a title on the left and buttons on the right, a card with a body and a footer, an empty state with a picture and an action. JSX is just a value, so you can pass it in any prop, not only children. Props used this way are often called slots.
PageHeader decides where things go: the layout, spacing and alignment. The page that uses it decides what goes there. Compare the alternative that teams drift into: showButton, buttonLabel, onButtonClick, buttonVariant, then showSecondButton the following month. Every new design needs a new prop and a release of the shared component. A slot handles cases nobody planned for.
Two details matter. First, the JSX in a slot is created by the parent, so its event handlers close over the parent's data. PageHeader never needs to know what Export does. Second, a slot element's state lives where it ends up rendered in the tree, inside PageHeader, so if the header stops rendering the slot, that state is gone.
Slots have a cost: they let callers put anything anywhere, which can break visual consistency in a design system. Shared libraries often mix both styles, with slots for content and a few typed props (variant, size) for things that must stay consistent. The Design & Architecture course's React lesson covers compound components, the next step up.
Dialog has props showCancel, cancelLabel, confirmLabel, confirmVariant, onConfirm and onCancel. Design now wants a third button, Save draft, on one screen. What is the most flexible change?Composition: building big from small
Composition means building complex components by combining simpler ones, instead of one giant component with lots of options. Here is a small product page and its component tree. Data flows down: each parent passes props to its children.
App owns the data: the store name, the cart count and the list of products.
A good split follows the single responsibility idea: each component does one thing. If you cannot name a component in two or three words, it is probably doing too much.
Match each JSX usage to the props object the component receives.
Props are read-only
A component must never change its own props. Writing props.count = 5 or title = title.toUpperCase() on a prop object breaks React's model: the parent owns that data, and React assumes rendering is a pure function of its inputs (same props in, same JSX out, no side effects). If a component needs a value that changes over time, that is state, which you will learn in the State unit.
Deriving a new value is fine, because it creates a new variable instead of changing the prop:
function Title({ text }: { text: string }) {
const shout = text.toUpperCase(); // fine: a new value
// text = "changed"; // never reassign or mutate props
return <h2>{shout}</h2>;
}ProductCard needs to show a sale price that is 20% off product.price. What should it do?Purity: render must be idempotent
"Pure" has a precise meaning in React. Components must be idempotent: called with the same props, state and context, they return the same JSX, and calling them changes nothing that existed before the call. React depends on this because it calls your components whenever it likes. It may render a component twice, throw away a render that was interrupted by something more urgent, render a screen in advance before it is shown, or skip a render and reuse the last result.
Here is a component that breaks the rule. It counts guests in a variable outside the component. Click the button, which only makes the parent render again.
Nothing about the cups changed, yet the numbers keep climbing. The output depends on how many times React called Cup, which is exactly what you cannot control. The fix is to make the number an input: <Cup guest={1} />.
What counts as breaking the rule during render:
- Changing props, state, or any variable or object that existed before the render started.
- Reading values that change without React knowing:
Date.now(),Math.random(),window.innerWidth,localStorage. They make output depend on when React calls you, and on a server-rendered site they cause hydration mismatches because the server and the browser get different answers. - Side effects: network requests, timers, analytics calls, writing to the DOM. These belong in event handlers, or in effects, which come later in the course.
Mutating something you created during this render is fine. Building an array with push inside the component and returning it is still pure, because nobody else can see that array yet.
React has a tool to find impurity early. In development, <StrictMode> (which Vite and Next.js templates turn on) calls each component function twice and keeps one result. A pure component gives the same answer both times. An impure one shows odd output that tells you something is wrong. Production renders once.
The impure Cup above runs inside <StrictMode> in development. What guest numbers do the three cups show on the first load?
let guest = 0;
function Cup() {
guest = guest + 1;
return <li>Tea cup for guest #{guest}</li>;
}
<StrictMode>
<Cup /><Cup /><Cup />
</StrictMode>Purity is also what React Compiler builds on. The compiler (version 1.0, stable since October 2025) memoises components and values for you at build time, so a component re-runs only when its inputs change. It assumes the Rules of React: components are idempotent, props and state are never mutated, and side effects stay out of render. If a component secretly reads a mutable module variable, the compiled version may hand back a cached result and never see the new value. The compiler's lint rules ship in eslint-plugin-react-hooks, and the compiler skips optimising components where it detects a violation, but it cannot detect all of them. Writing pure components is still your job.
A key resets a component
You met key in the lists lesson. It works on any element, not only inside an array. React identifies a component by its position in the tree and its key. Give it a different key and React treats it as a different component: it throws the old one away, with all its state, and mounts a fresh one.
Type a message to Ada below, then switch to Sam. Then untick the box and try again.
Without the key, the draft you wrote to Ada is still there when you switch to Sam: same component, same position, so React keeps its state. In a chat app that is a bug that sends a message to the wrong person. With key={contact.id}, each contact gets its own fresh MessageBox.
Reach for a key whenever "a different thing" should start clean: an edit form for a different user (key={user.id}), a game's play-again button (key={round}), a wizard that restarts. The cost is a full remount: the DOM inside is rebuilt and any effects run again. That is cheap for a form and wasteful for a large subtree on every keystroke. The conditional rendering lesson explains the position rule in detail, and the lifting state lesson shows when a key beats copying props into state.
Pricing cards
Write a reusable Card component and use it three times.
Card takes title (string), an optional price (number, default 0) and optional children. It renders:
<article class="card">
<h3>{title}</h3>
<p class="price">Free or $12</p>
...children
</article>The price line says Free when the price is 0, otherwise a dollar sign and the number ($12).
In App, render three cards in this order:
- title
Starter, no price passed - title
Pro, price12 - title
Team, price49, with the child<p>Up to 10 seats</p>
- component
- A function with a capitalised name that returns JSX. Used like a tag:
<Card />. - props
- The object of inputs a parent passes to a component, written like attributes. Read-only inside the component.
- children
- The special prop holding whatever is placed between a component's opening and closing tags.
- composition
- Building complex UIs by combining small, focused components instead of one big configurable one.
- pure component
- Given the same props, it returns the same JSX and changes nothing outside itself during render.
- idempotent
- Calling it again with the same inputs gives the same result. React assumes every component is.
- slot
- A prop that takes JSX, like
actionsorfooter, so the caller decides what fills that part of the layout. - rest props
- Collecting leftover props with
...restand spreading them onto an element. Later props win. - StrictMode
- A development-only wrapper that renders components twice, among other checks, to expose impure code.