Skip to content

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.

20 min read0/7 questions

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.

React
function Greeting() { return <p>Hello from a component!</p>;} export default function App() { return ( <div> <Greeting /> <Greeting /> <Greeting /> </div> );}

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).

Quick check
You write function card() { ... } and render <card />. What happens?
Need a nudge? A hint rules out a wrong answer.

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.

React
type PriceTagProps = { label: string; cents: number }; function PriceTag(props: PriceTagProps) { return ( <p> {props.label}: ${(props.cents / 100).toFixed(2)} </p> );} export default function App() { return ( <div> <PriceTag label="Coffee" cents={350} /> <PriceTag label="Bagel" cents={275} /> </div> );}

<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.

React
type ButtonProps = { label: string; size?: "small" | "large"; disabled?: boolean }; function Button({ label, size = "small", disabled = false }: ButtonProps) { const padding = size === "large" ? "12px 24px" : "4px 10px"; return ( <button style={{ padding }} disabled={disabled}> {label} </button> );} export default function App() { return ( <div style={{ display: "flex", gap: 8 }}> <Button label="Save" /> <Button label="Publish" size="large" /> <Button label="Delete" disabled /> </div> );}

A prop written with no value (disabled) means true. The ? in the TypeScript type marks a prop as optional.

Predict the outputJavaScript

What text does this render?

function Badge({ text = "new", count = 1 }) {
return <span>{text} x{count}</span>;
}

<Badge count={3} />
Need a nudge? Hints walk you through it.

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.

Predict the outputJavaScript

Which type does the input get, and is it disabled?

function Field(props) {
return <input type="text" {...props} disabled={false} />;
}

<Field type="email" disabled />
Need a nudge? Hints walk you through it.

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.

React
import type { ReactNode } from "react"; function Card({ title, children }: { title: string; children: ReactNode }) { return ( <section style={{ border: "1px solid #ddd", borderRadius: 8, padding: 12, marginBottom: 8 }}> <h3 style={{ margin: "0 0 6px" }}>{title}</h3> {children} </section> );} export default function App() { return ( <> <Card title="Profile"> <p>Ada, backend engineer.</p> </Card> <Card title="Stats"> <ul> <li>12 projects</li> <li>340 commits</li> </ul> </Card> </> );}

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.

React
import type { ReactNode } from "react"; type PageHeaderProps = { title: string; actions?: ReactNode; children?: ReactNode }; function PageHeader({ title, actions, children }: PageHeaderProps) { return ( <header style={{ borderBottom: "1px solid #ddd", paddingBottom: 8, marginBottom: 12 }}> <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8 }}> <h2 style={{ margin: 0 }}>{title}</h2> {actions && <div style={{ display: "flex", gap: 6 }}>{actions}</div>} </div> {children && <p style={{ margin: "4px 0 0", opacity: 0.7 }}>{children}</p>} </header> );} export default function App() { return ( <> <PageHeader title="Invoices" actions={ <> <button onClick={() => alert("Exporting")}>Export</button> <button onClick={() => alert("New invoice")}>New invoice</button> </> } > 12 unpaid, 3 overdue. </PageHeader> <PageHeader title="Settings" /> </> );}

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.

Quick check
A shared 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?
Need a nudge? A hint rules out a wrong answer.

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.

A product page as a component tree
AppLogoCartBadgeprops: countHeaderprops: storeNamePriceTagprops: centsProductCardprops: productPriceTagprops: centsProductCardprops: productProductListprops: productsroot

App owns the data: the store name, the cart count and the list of products.

1/4

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 the pairs0/4 matched

Match each JSX usage to the props object the component receives.

Choose an item, then its match on the other side.

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>;
}
Quick check
A ProductCard needs to show a sale price that is 20% off product.price. What should it do?
Need a nudge? A hint rules out a wrong answer.

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.

React
import { useState } from "react"; let guest = 0; function Cup() { guest = guest + 1; // changes a value that existed before render return <li>Tea cup for guest #{guest}</li>;} export default function App() { const [renders, setRenders] = useState(1); return ( <div> <ul> <Cup /> <Cup /> <Cup /> </ul> <button onClick={() => setRenders(renders + 1)}>Render again ({renders})</button> </div> );}

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.

Predict the outputJavaScript

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>
Need a nudge? Hints walk you through it.

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.

React
import { useState } from "react"; const CONTACTS = [ { id: "ada", name: "Ada" }, { id: "sam", name: "Sam" },]; function MessageBox({ to }: { to: string }) { const [draft, setDraft] = useState(""); return <input aria-label={`Message to ${to}`} placeholder={`Message ${to}`} value={draft} onChange={(e) => setDraft(e.target.value)} />;} export default function App() { const [contactId, setContactId] = useState("ada"); const [resetOnSwitch, setResetOnSwitch] = useState(true); const contact = CONTACTS.find((c) => c.id === contactId)!; return ( <div style={{ display: "grid", gap: 8, maxWidth: 320 }}> <div style={{ display: "flex", gap: 6 }}> {CONTACTS.map((c) => ( <button key={c.id} onClick={() => setContactId(c.id)} style={{ fontWeight: c.id === contactId ? 700 : 400 }}> {c.name} </button> ))} </div> <label> <input type="checkbox" checked={resetOnSwitch} onChange={(e) => setResetOnSwitch(e.target.checked)} /> Use key=contact.id </label> {resetOnSwitch ? <MessageBox key={contact.id} to={contact.name} /> : <MessageBox to={contact.name} />} </div> );}

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.

ChallengeEasy

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:

  1. title Starter, no price passed
  2. title Pro, price 12
  3. title Team, price 49, with the child <p>Up to 10 seats</p>
React
import type { ReactNode } from "react"; type CardProps = { title: string; price?: number; children?: ReactNode }; function Card(props: CardProps) { // Destructure the props, give price a default, and return the card. return null;} export default function App() { return <div>{/* Render the three cards here */}</div>;}
Key terms
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 actions or footer, so the caller decides what fills that part of the layout.
rest props
Collecting leftover props with ...rest and spreading them onto an element. Later props win.
StrictMode
A development-only wrapper that renders components twice, among other checks, to expose impure code.