Sub topic 2
Rendering Is a Pure Calculation of UI from Props and State
This chapter assumes you can write function components, pass props, use useState, and read JSX. It covers one idea: a component's render is a calculation. Given the same props and state, it must return the same JSX, and it must not change anything outside itself. Later chapters (the render and commit phases, Strict Mode, concurrent rendering) depend on this rule.
What "pure" means for a component
A pure function has two properties:
- Given the same inputs, it returns the same output.
- It does not change anything that existed before it was called.
For a React component, the inputs are props, state, and context. The output is the JSX the component returns. React expects every render to follow this contract.
function Greeting({ name }) {
return <h1>Hello, {name}</h1>;
}Greeting is pure. Rendering it with name="Ada" always produces the same heading, and nothing outside the function changes.
Compare it with this component:
let calls = 0;
function BadGreeting({ name }) {
calls = calls + 1; // changes a variable that existed before the render
return <h1>Hello, {name} (call {calls})</h1>;
}BadGreeting returns different output for the same props, because it reads and writes a variable outside itself. If React renders it twice, the two results differ. React is allowed to render a component more than once, so the screen can show wrong values.
Why React demands purity
React treats rendering as a calculation it can schedule, repeat, pause, or throw away. It makes this promise to itself: calling your component has no side effects that anyone could observe. That promise allows several behaviors:
- Re-running a render. React may call a component again, for example when a parent re-renders or when Strict Mode double-invokes it in development.
- Skipping a render. If inputs have not changed, React can reuse the previous result (see the memoization chapter).
- Discarding a render. With concurrent rendering, React can start a render, then abandon it when a more urgent update arrives. The abandoned result is never shown.
- Rendering in any order. A component should not depend on whether a sibling rendered before or after it.
If a render changed something outside itself, each of these behaviors would leave visible damage. A render that was thrown away would still have changed the outside world.
What counts as a side effect in render
The rule applies to code that runs while React calls your component. This includes the function body, and also functions you call from it, such as the callback you pass to map, useMemo, or a useState initializer.
Common violations:
| Violation | Why it breaks | Where it belongs |
|---|---|---|
| Modifying a variable declared outside the component | Output depends on how many times render ran | Local variable, or state |
| Mutating props or state objects | Other code that holds the same object sees the change | Copy the object, then set new state |
| Calling `fetch` or starting a timer | Runs once per render call, including discarded ones | `useEffect` or an event handler |
| Reading `Math.random()` or `Date.now()` and showing the result | Output differs on every call | State, or an effect that sets state |
| Writing to the DOM (`document.title = ...`) | React does not know about the change | `useEffect` |
| Writing to `localStorage` | Observable side effect | Event handler or effect |
Two kinds of mutation are allowed because they cannot be observed from outside.
Local mutation is fine
A variable created during the current render and used only by that render is safe to change. React calls this local mutation.
function TagList({ tags }) {
const items = []; // created during this render
for (const tag of tags) {
items.push(<li key={tag}>{tag}</li>);
}
return <ul>{items}</ul>;
}items is created fresh on every call and never shared. Every render with the same tags returns the same list. This is pure by the definition above.
Inputs are read-only
Props and state belong to React. Treat them as read-only snapshots of a single render.
function SortedNames({ names }) {
// Wrong: sort() mutates the array that the parent owns
// const sorted = names.sort();
// Right: copy first, then sort the copy
const sorted = [...names].sort();
return (
<ul>
{sorted.map(name => (
<li key={name}>{name}</li>
))}
</ul>
);
}Array.prototype.sort sorts in place. Calling it on a prop changes the parent's array. The parent's data changes during the child's render, which no other component can predict. Copying with the spread operator avoids that. toSorted is an alternative in current JavaScript runtimes.
Updating state follows the same rule. State is replaced, not edited:
import { useState } from 'react';
function Cart() {
const [items, setItems] = useState([]);
function addItem(item) {
// Wrong: items.push(item); setItems(items);
// React sees the same array reference and may skip the re-render.
setItems([...items, item]);
}
return (
<>
<button onClick={() => addItem('apple')}>Add apple</button>
<p>{items.length} items</p>
</>
);
}React compares the new state with the old using Object.is. A mutated array is still the same reference, so React sees no change. A new array is a different reference, so React re-renders.
Where side effects go
Side effects are legitimate. They need to run at a point where React is not treating the code as a repeatable calculation.
- Event handlers. Code that runs because the user did something. Handlers are not part of rendering, so they can mutate, call APIs, and set state.
- Effects. Code in
useEffectruns after React has committed the result to the screen. Use effects for work that must happen because the component is displayed, such as subscriptions or settingdocument.title.
import { useEffect, useState } from 'react';
function PageTitle({ title }) {
const [clicks, setClicks] = useState(0);
useEffect(() => {
document.title = `${title} (${clicks})`;
}, [title, clicks]);
return (
<button onClick={() => setClicks(c => c + 1)}>
Clicked {clicks} times
</button>
);
}The render body only calculates JSX. The title change lives in the effect, and the click handler is where the state update starts.
A common trap: shared mutable state across components
Impurity often hides in module-level variables, because the bug only shows when several components use the same value.
let guestCount = 0;
function Cup() {
guestCount = guestCount + 1; // mutates shared module state during render
return <h2>Guest #{guestCount}</h2>;
}
export default function TeaSet() {
return (
<>
<Cup />
<Cup />
<Cup />
</>
);
}On the first render this shows guests 1, 2, 3. When TeaSet renders again, the module variable continues from 3 and shows 4, 5, 6. In development, Strict Mode renders components twice and shows different numbers than you expect. The fix is to pass the value as a prop:
function Cup({ guest }) {
return <h2>Guest #{guest}</h2>;
}
export default function TeaSet() {
return (
<>
<Cup guest={1} />
<Cup guest={2} />
<Cup guest={3} />
</>
);
}Now each Cup depends only on its props. React can render the three cups in any order, or skip one, and the output stays correct.
Hooks and the rules of render
Hooks follow the same contract. Call them at the top level of the component, in the same order on every render. React identifies each hook by its call position, so a hook inside a condition or loop breaks the matching between render calls.
Reading context and using useState and useMemo are fine during render. They are inputs React supplies. Hooks that cause side effects, like useEffect, register work that React runs later, so calling them does not make the render impure.
Debugging impure renders
Symptoms of an impure render:
- A value counts up by two, or a log appears twice, in development only. Strict Mode intentionally renders twice to expose the problem.
- Two components show inconsistent values from the same source.
- A change to an array or object does not update the screen.
- A UI value differs between the first render and a re-render with no real change.
When you see these, search the component and the functions it calls for writes to outer variables, in-place mutation of props or state (push, splice, sort, reverse, assignment to a property), and calls to Math.random(), Date.now(), or network functions.
Summary of the rules
- Calculate JSX from props, state, and context only.
- Do not change variables, objects, or arrays that existed before the render started.
- Copy before you sort, reverse, or edit, and set state with a new value.
- Put network calls, timers, and DOM writes in event handlers or effects.
- Mutating values you created during the current render is fine.
Exercise
This component shows a different total each time its parent re-renders, even though prices has not changed. Name the two problems and give a fix.
function Total({ prices }) {
let sum = 0;
prices.reverse();
for (const p of prices) sum += p;
return <p>{sum} ({prices[0]} first)</p>;
}
Show answer
prices.reverse() reverses the array in place, so it mutates a prop the parent owns, and the "first" item flips on every render. (The sum itself is stable because sum is a local variable, which is allowed.) The fix is to copy before reversing: const ordered = [...prices].reverse();, then use ordered for display. If order does not matter, remove the reverse call.
Exercise
A component sets document.title directly in its function body. Why is that wrong, and where should the line go?
Show answer
Rendering must be a repeatable calculation, and React may run, repeat, or discard a render. Writing to the DOM during render is a side effect that React cannot track, so it can run for renders that are never shown. Move it into useEffect(() => { document.title = title; }, [title]);, which runs after the result is committed.