Components and props

Composition, children, lists and why render must be pure.

Builds on Effects from scratch.

Part 2 ended with a toy React that could call function components, diff their output, keep hook state on fibers and run effects after commit. From here on we use the real thing: React 19.3, written in TypeScript. Almost everything in this chapter will feel familiar, because you built it. What's new is the set of rules real React expects your components to follow, and the main one is that rendering must be pure.

This chapter covers components and props as React actually ships them: how data flows down, how children turns components into composable containers, how lists, conditionals and fragments work, what React 19 changed for custom elements, and why a component that touches anything outside its own inputs during render will eventually show the wrong thing.

The problem: a component that counts its own calls#

Here's a component that looks harmless. It keeps a counter in a module variable and bumps it every time it renders, so each cup gets a "unique" guest number.

An impure component under StrictMode
let guest = 0;

function Cup() {
  // Bad: changes a variable that existed before this render.
  guest = guest + 1;
  return <h3>Tea cup for guest #{guest}</h3>;
}

export default function App() {
  return (
    <>
      <Cup />
      <Cup />
      <Cup />
    </>
  );
}

You'd expect #1, #2 and #3. You get #2, #4 and #6. The sandbox wraps the app in <StrictMode>, which in development calls each component function twice and keeps one result. A pure function wouldn't care how many times it's called. This one does, so the extra call exposes it.

Remove strict in your head and the numbers come out right on the first paint. That's the trap: the bug is still there. The moment anything re-renders those cups (a parent's state change, a transition that React restarts, a Suspense retry), the numbers drift again. StrictMode just makes the drift happen on day one instead of in production.

What StrictMode's second render catches
Module scopelet guest = 0shared by every call,outside React's controlCalls to Cup()Screencall 1call 2call 1call 2call 1call 2
Step 1 of 5

React calls App. App returns three <Cup /> elements, plain objects. Cup itself hasn't run yet, and the module variable guest is 0.

What a component is, in real React#

A component is a function that takes one argument, an object of props, and returns something React can render: elements, strings, numbers, null, arrays of those, or fragments. You built exactly this in Rendering elements: render() saw an element whose type was a function and called it with props.

type GreetingProps = {
  name: string;
  excited?: boolean; // optional prop
};

function Greeting({ name, excited = false }: GreetingProps) {
  return <p>Hello, {name}{excited ? "!" : "."}</p>;
}

// <Greeting name="Ada" excited /> compiles to
// jsx(Greeting, { name: "Ada", excited: true })

A few things to notice:

  • Names start with a capital letter. JSX uses that to decide between a string type ("div") and a variable (Greeting). <greeting /> would create an unknown DOM tag.
  • Props are one object, so destructuring in the signature is the normal style. Defaults go in the destructuring (excited = false). React 19 removed defaultProps for function components, so this is now the only way.
  • Typing pattern: describe props with a type (or interface) and annotate the parameter. Don't reach for React.FC; it adds nothing you need and used to add an implicit children. Return types are inferred.

React calls your component. You never call it yourself (Greeting({ name: "Ada" }) would run its hooks inside the caller, which breaks the hook cursor you built in Hooks from scratch). You return a description, and React decides when to call the function and what to do with the result.

Props flow down and are read-only#

Props are the arguments a parent passes to a child. They flow one way: down. The child can read them, but it must not change them. React freezes the props object in development, so props.name = "x" throws in strict JavaScript. Nested objects and arrays inside props aren't frozen, though, so mutating props.items slips through silently. That's the version of this bug people actually ship (exercise below).

If a child needs to tell the parent something, the parent passes a function down as a prop and the child calls it. That's the subject of Events. If the child needs its own changing value, that's state, in State.

Composition with children#

Any JSX between a component's opening and closing tags arrives as the children prop. That one rule is how React builds layouts without inheritance: a component can wrap content it knows nothing about.

Children and named slots
import type { ReactNode } from "react";

type CardProps = {
  title: string;
  actions?: ReactNode; // a named slot
  children: ReactNode; // the default slot
};

function Card({ title, actions, children }: CardProps) {
  return (
    <section style={{ border: "1px solid #d6d3d1", borderRadius: 8, padding: 12, marginBottom: 12 }}>
      <header style={{ display: "flex", justifyContent: "space-between" }}>
        <strong>{title}</strong>
        {actions}
      </header>
      <div style={{ marginTop: 8 }}>{children}</div>
    </section>
  );
}

export default function App() {
  return (
    <>
      <Card title="Now reading" actions={<button>Finish</button>}>
        <p>Designing Data-Intensive Applications</p>
      </Card>
      <Card title="Note">
        Cards don't know what's inside them. That's the point.
      </Card>
    </>
  );
}

Typing pattern: ReactNode is the type for "anything React can render" (elements, strings, numbers, null, arrays). Use it for children and for slot props like actions. Use ReactElement only when you really need an element object, which is rare.

Composition solves problems that look like they need something fancier. Before you reach for context to pass data through five layers, check whether the middle layers could just take children and let the top component place the data-hungry child directly. We'll come back to this in Context, and it matters for performance too: elements passed in as children were created by whoever rendered the wrapper, not by the wrapper itself, so a re-render of the wrapper alone doesn't re-create them.

Rendering lists#

A list is an array of elements. map is the usual way to make one, and each element needs a key that's stable and unique among its siblings.

import { books } from "guide-tools";

function BookList() {
  return (
    <ul>
      {books.map((book) => (
        <li key={book.id}>
          {book.title} ({book.year})
        </li>
      ))}
    </ul>
  );
}

You implemented why keys matter in Keys: the reconciler matches old and new children by key, so a stable id keeps each item's DOM and state attached to the right data when the list reorders. Use the data's id. Index keys are fine only for lists that never reorder, insert or delete in the middle. Math.random() keys are always wrong, because every render gets fresh keys and React remounts every item.

Keys aren't props. book.key doesn't exist inside the child; if the child needs the id, pass it separately.

Conditional rendering#

JSX is just expressions, so conditionals are just JavaScript:

function Status({ count, loading }: { count: number; loading: boolean }) {
  if (loading) return <p>Loading…</p>; // early return

  return (
    <div>
      {count > 0 ? <p>{count} unread</p> : <p>All caught up</p>}
      {count > 99 && <span>99+</span>}
    </div>
  );
}

null, undefined, true and false render nothing. Numbers and strings render as text, and that includes 0. So {count && <Badge />} renders a stray 0 when count is zero. Write {count > 0 && <Badge />} instead.

Fragments#

A component returns one thing. When you want to return several siblings without a wrapper div (which can break table markup or flex layouts), wrap them in a fragment:

import { Fragment } from "react";

function Row() {
  return (
    <>
      <td>Title</td>
      <td>Year</td>
    </>
  );
}

function Glossary({ terms }: { terms: { id: string; term: string; def: string }[] }) {
  return (
    <dl>
      {terms.map((t) => (
        // The short syntax can't take props, so a keyed fragment is spelled out.
        <Fragment key={t.id}>
          <dt>{t.term}</dt>
          <dd>{t.def}</dd>
        </Fragment>
      ))}
    </dl>
  );
}

A fragment produces no DOM node. In the fiber tree you built it's just a node whose children get placed directly into the parent. React 19.3 Fragment can also take a ref, which gives you a handle over its children without a wrapper element. That's covered in Refs.

Custom elements in React 19 React 19.0#

Web components (tags with a dash, like <my-rating>) finally work the way you'd expect. Before 19, React passed every prop as a string attribute, so objects arrived as "[object Object]" and you needed a ref to set properties by hand. React 19 changed the rules:

  • On the client, if the element instance has a property with the prop's name, React sets the property (so arrays and objects arrive intact). Otherwise it sets an attribute.
  • When rendering on the server, primitive values (strings, numbers, true) become attributes; objects, functions and false are left out.
  • Custom events are listened to with an on prefix followed by the exact event name, case and dashes included: onrating-change listens for rating-change events.
A custom element with a property and a custom event
import { useState } from "react";

class StarRating extends HTMLElement {
  // Properties React can see on the instance, so it sets them as properties.
  labels: string[] = [];
  _value = 0;
  get value() {
    return this._value;
  }
  set value(v: number) {
    this._value = v;
    this.render();
  }
  connectedCallback() {
    this.render();
  }
  render() {
    this.innerHTML = "";
    for (let i = 1; i <= 5; i++) {
      const b = document.createElement("button");
      b.textContent = i <= this.value ? "★" : "☆";
      b.title = this.labels[i - 1] ?? "";
      b.onclick = () => this.dispatchEvent(new CustomEvent("rating-change", { detail: i }));
      this.append(b);
    }
  }
}
if (!customElements.get("star-rating")) customElements.define("star-rating", StarRating);

declare global {
  namespace React.JSX {
    interface IntrinsicElements {
      "star-rating": any;
    }
  }
}

export default function App() {
  const [rating, setRating] = useState(3);
  return (
    <>
      <star-rating
        value={rating}
        labels={["Bad", "Meh", "Fine", "Good", "Great"]}
        onrating-change={(e: CustomEvent<number>) => {
          console.log("rating-change", e.detail);
          setRating(e.detail);
        }}
      />
      <p>Rating: {rating}</p>
    </>
  );
}
Nothing logged yet.

Click a star. React set labels as a real array property (hover a star to see its title), and the onrating-change prop subscribed to the element's custom event. This demo uses useState, which State covers properly; here it's only there to re-render. The declare global block is the typing pattern for custom tags: add them to React.JSX.IntrinsicElements so TypeScript accepts the tag. Real projects type the props instead of using any.

Why render must be pure#

Here's the rule, stated precisely. During render, a component must:

  1. Return the same output for the same inputs. Inputs are props, state and context.
  2. Not change anything that existed before the render started. No mutating props, module variables, objects that came from outside, or the DOM.

Creating and mutating new local objects inside render is fine. const list = []; list.push(x) is pure from the outside, because nobody else can see list until you return it.

Why does React care so much? Because of what you built in Part 2. In Fiber rendering became interruptible: React may start rendering a component, throw the work away when something more urgent comes in, and start over. Concurrent features (transitions, Suspense, <Activity>) depend on this. React may also render a component more than once before committing, or render it and never commit. All of that is only safe if calling your function has no effects. Side effects belong in event handlers, which run because the user did something, or in effects, which run after commit (Effects).

  • Render is a calculation. Same props, state and context in, same JSX out.
  • React may call your component zero, one or several times per commit. Don't count on the number.
  • Mutations of fresh local values are fine. Mutations of anything that existed before render are not.

What StrictMode does about it#

<StrictMode> is a development-only wrapper that turns hidden impurity into visible bugs. For rendering, it calls each component function (and the initializer and updater functions you'll meet in State) twice, then uses one of the results. If both calls return the same thing, nothing changes. If they don't, you see it. It does the same kind of double run for effects, which Effects explains. None of this happens in production builds.

Fix itThe list that sorts its neighbor

ByYear shows books sorted by year. AsAdded shows the same books in their original order. But both lists come out sorted. Fix ByYear so it stays pure, then press Check.

import { books } from "guide-tools";

type Book = (typeof books)[number];

function ByYear({ items }: { items: Book[] }) {
  const sorted = items.sort((a, b) => a.year - b.year);
  return (
    <ul data-list="by-year">
      {sorted.map((b) => (
        <li key={b.id}>{b.year}: {b.title}</li>
      ))}
    </ul>
  );
}

function AsAdded({ items }: { items: Book[] }) {
  return (
    <ul data-list="as-added">
      {items.map((b) => (
        <li key={b.id}>{b.title}</li>
      ))}
    </ul>
  );
}

export default function App() {
  return (
    <>
      <h4>By year</h4>
      <ByYear items={books} />
      <h4>As added</h4>
      <AsAdded items={books} />
    </>
  );
}

Pitfalls#

Check your understanding#

PredictLogs under StrictMode

This app renders inside <StrictMode> in development. How many times does "render Title" appear in the console after the first load, and what does the heading say?

let renders = 0;

function Title() {
  renders++;
  console.log("render Title");
  return <h1>Rendered {renders} times</h1>;
}

export default function App() {
  return <Title />;
}
let renders = 0;

function Title() {
  renders++;
  console.log("render Title");
  return <h1>Rendered {renders} times</h1>;
}

export default function App() {
  return <Title />;
}
Nothing logged yet.
Quick checkEmpty cart

`cart.length` is 0. What does `<div>{cart.length && <CartSummary />}</div>` render?

Quick checkWhere children come from

`Layout` re-renders because its own state changed. It renders `{children}`, which `App` passed in. Does React call the components inside `children` again?

Explain it out loudWhy must render be pure?

An interviewer asks: "React docs say components must be pure. What does that mean, and why does React need it?"

Interview angle

Say it in 30 seconds

A component is a function from props to a description of UI, and React decides when to call it. Props flow down and are read-only; children and slot props let you compose components without inheritance. Lists need stable keys from the data, conditionals are plain JavaScript, and fragments group siblings without a DOM node. The rule underneath all of it is purity: same inputs, same output, and no changes to anything that existed before render. React relies on that because concurrent rendering may repeat, interrupt or discard renders, and StrictMode double-renders in development to catch components that break it.

What's the difference between props and state?

basic

Is mutating something during render always a bug? Where exactly is the line, and how does StrictMode help you find it?

intermediate

How do you use composition in React, and why is it preferred over inheritance?

intermediate

A list item component needs its book's id. Why can't it read props.key?

basic

What changed for custom elements in React 19?

senior

Why does {count && <Badge />} sometimes render a 0?

basic

Recap#

  • A component is a function from props to a description of UI. React calls it; you don't.
  • Props flow down and are read-only. Children (and named slot props typed as ReactNode) are how you compose without inheritance.
  • Lists need stable keys from the data. Conditionals are plain JavaScript, but watch for 0 &&. Fragments group siblings without a DOM node.
  • React 19 sets custom element props as properties when the element declares them and listens to custom events through on plus the exact event name.
  • Render must be pure because React may run it any number of times, interrupt it or discard it. StrictMode double-renders in development to expose impure components.

Sources#