Chapter 5 Β· Describing the UI

Pure Components & the UI Tree

One rule keeps React apps predictable: components must be "pure". Then you'll see how React views your app as a tree.

You will learn
  • What "pure" means, and why React needs it
  • How to spot and fix impure components
  • Where side effects belong instead
  • The render tree and the module dependency tree

What is a pure function?

In maths, a formula like y = 2x always gives the same answer for the same input: if x = 3, then y is always 6. A pure function works the same way. It has two properties:

  1. Same inputs β†’ same output. Given the same props, a component always returns the same JSX.
  2. It minds its own business. It doesn't change anything that existed before it was called: no outside variables, no objects passed in.

Think of a component as a recipe: if you follow it and don't add new ingredients halfway, you get the same dish every time.

An impure component (and the bug it causes)

You might expect guests #1, #2 and #3. But React can call components any number of times and in any order. In development, StrictMode calls each one twice, so you'd see #2, #4, #6. Calling Cup gives a different result every time, so it's unpredictable.

The fix: pass the data in as a prop.

How StrictMode helps In development, React calls each component function twice. A pure component gives the same result both times, so you won't notice anything. An impure one misbehaves, which reveals the bug early. That's why your console.logs sometimes print twice.

Local mutation is fine

Changing a variable you created during this render is perfectly OK. Nobody outside can see it:

The problem is only changing things that existed before the render: outside variables, props, state, or other components' data.

Where side effects go

Changing the screen, starting an animation, fetching data, writing to localStorage: these are side effects, things that happen "on the side" rather than during rendering. Apps need them, of course. They just don't belong in the component body.

Rules of thumb for the component body
  • Don't change props, state or outside variables.
  • Don't call fetch, setTimeout or document.title = ... directly in the body.
  • Just calculate and return JSX.

Why purity matters

Your UI as a tree

React, like the browser, models UI as a tree: things that contain other things. Seeing this tree helps you understand how data flows, where state lives, and what re-renders.

The render tree

Given this app:

React builds this render tree, which shows which component rendered which:

The tree contains only components. HTML tags like <div> are left out because they're just the output.

The module dependency tree

A second, different tree shows which file imports which:

Build tools such as Vite use this tree to bundle your code into the files the browser downloads. A big dependency tree means a big download, so be careful about importing heavy libraries everywhere.

More examples

Example 1: mutating a prop object (impure) vs deriving (pure)

Example 2: sort() is a hidden mutation

Watch out for array methods that change the original: sort, reverse, push, pop, splice, shift, unshift.

Example 3: touching the page during render

Example 4: pure helpers make components simpler

Example 5: how conditions change the render tree

Same code, but a different tree on each render. That matters a lot for state (Chapter 10).

Recap

  • A pure component returns the same JSX for the same props and doesn't change anything that existed before it ran.
  • Creating and changing local variables during render is fine.
  • Side effects go in event handlers first, and in useEffect only as a last resort.
  • StrictMode double-calls components in development to catch impurity.
  • The render tree shows who renders whom. The dependency tree shows who imports whom.

Exercises

1. Find the impurity

Why does "Create Story" appear more and more times? Fix it.

Show solution

stories is a prop, an array owned by the parent. push changes that array on every render, so items pile up. Copy it first, so you only change your own local array:

2. Draw your tree

Open React DevTools β†’ Components in your sample-test-react app. Draw its render tree on paper. Which components are leaves?

Show answer

Roughly App β†’ Gallery β†’ Profile Γ—3, and App β†’ TodoList when the pop-up is open. Profile and TodoList are leaves because they render no components of their own.

3. Pure or not? 🟒 easy

For each component, say whether it's pure.

Show answer

A: pure. B: impure (it changes an outside variable). C: pure (it changes only its own local copy). D: impure (it mutates a prop).

4. Fix the sorted list 🟒 easy

Show solution

5. Fix the render counter 🟒 easy

Show solution

Pass the number in as a prop from the parent: function Ticket({ id, name }), then render <Ticket id={1} name="Asha" />, or tickets.map((t, i) => <Ticket key={t.id} id={i + 1} name={t.name} />).

6. Don't change the person 🟒 easy

Show solution

7. Move the side effect 🟑 medium

What's wrong, and how do you fix it?

Show solution

It writes to storage every time it renders, even without a click. Move it into the click handler:

8. Extract pure helpers 🟑 medium

Write two pure functions: getInitials('Hedy Lamarr') β†’ "HL", and pluralize(count, word) β†’ "1 item" / "3 items". Use both in a component that shows "HL has 3 items".

Show solution

9. Draw the render tree 🟑 medium

Draw the tree for when user is null and there are 2 products. Which components are leaves?

Show answer

Leaves (assuming they render no components of their own): Header, LoginButton and both ProductItems.

10. Your project's dependency tree πŸ”΄ hard

For your sample-test-react app, list every file and what it imports, starting from main.jsx. Draw it as a tree. Which file would you split first if the bundle got too big?

Show example answer

App.jsx holds most of the components (Gallery, TodoList…), so moving each into its own file under components/ is the natural first split.