Sub topic 14
Keeping components pure
This chapter assumes you can write function components, pass props, and use useState. It covers what "pure" means for a component, why React relies on it, and the mistakes that break it.
What pure means
A component is pure when it follows two rules:
- Same inputs, same output. Given the same props, state, and context, it returns the same JSX every time.
- No side effects during rendering. Rendering does not change anything that existed before it started.
The first rule is the same idea as a mathematical function. The second rule limits what the body of the component may do. Creating new local variables during a render is fine. Changing a variable declared outside the component is not.
function Cup({ guest }) {
return <h2>Tea cup for guest #{guest}</h2>;
}
export default function TeaSet() {
return (
<>
<Cup guest={1} />
<Cup guest={2} />
<Cup guest={3} />
</>
);
}Cup only reads its prop. Rendering it ten times, or in any order, gives the same results.
Why React expects purity
React calls your component function itself. You do not control when, how often, or in what order it runs. Several features depend on that freedom:
- Re-renders. A state change re-runs the component. The output must depend only on the current inputs.
- Skipping work. React can reuse a previous result when inputs have not changed. This only works if the result is predictable.
- Strict Mode. In development, React renders each component twice on purpose. A pure component gives identical results both times. An impure one shows its bug immediately.
- Concurrent rendering. React may start a render and then discard it, for example when a more urgent update arrives. Side effects from a discarded render would still have happened.
The rest of the chapter shows what goes wrong when the rules are broken.
Mutating outside variables
This is the classic impure component.
let guestCount = 0;
function Cup() {
guestCount = guestCount + 1; // Mutates a variable outside the component
return <h2>Tea cup for guest #{guestCount}</h2>;
}
export default function TeaSet() {
return (
<>
<Cup />
<Cup />
<Cup />
</>
);
}The output depends on how many times React has called Cup before. In Strict Mode each component renders twice, so the guests are numbered 2, 4, 6 instead of 1, 2, 3. The fix is to pass the value in as a prop, as the first example did.
Other external things that count as mutation during render:
- Assigning to a module-level variable or a property of an imported object.
- Writing to
document,window, orlocalStorage. - Sending a network request or starting a timer.
- Logging that other code depends on.
Impure inputs: time and randomness
Calling Math.random() or Date.now() in the render body makes the output differ between calls even when props are the same.
function Clock() {
// Impure: each render can produce a different result
return <p>{new Date().toLocaleTimeString()}</p>;
}This does not corrupt anything outside the component, but it breaks rule one. The displayed time does not update on its own either, because nothing triggers a re-render. If you need a changing value, keep it in state, update it from an effect or an event handler, and render the state. Effects are covered in a later tutorial. If you need a random or time-based value that must stay stable, create it once, for example as an initial state value, or pass it in as a prop.
Local mutation is fine
Mutating something you created during the same render is allowed. Nobody else can observe it.
function TeaGathering() {
const cups = [];
for (let i = 1; i <= 3; i++) {
cups.push(<Cup key={i} guest={i} />);
}
return <section>{cups}</section>;
}
function Cup({ guest }) {
return <h2>Tea cup for guest #{guest}</h2>;
}cups is created inside TeaGathering, filled, and returned. It is discarded or replaced on the next render. This is called local mutation.
Do not mutate props or state
Props and state belong to React and to the parent component. Treat them as read-only.
function List({ items }) {
items.sort(); // Bug: sorts the parent's array in place
return (
<ul>
{items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
}sort changes the array in place. The parent now holds a reordered array it did not ask for, and other components reading it see the change. Copy first:
function List({ items }) {
const sorted = [...items].sort();
return (
<ul>
{sorted.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
}State has an additional rule. React decides whether to re-render by comparing the new state value to the old one by reference. If you mutate an object or array in place and pass the same reference to the setter, React sees no change.
import { useState } from 'react';
function Tags() {
const [tags, setTags] = useState(['react']);
function addBroken() {
tags.push('jsx'); // Mutates existing array
setTags(tags); // Same reference, so no re-render
}
function addCorrect() {
setTags([...tags, 'jsx']); // New array
}
return (
<div>
<button onClick={addBroken}>Broken add</button>
<button onClick={addCorrect}>Correct add</button>
<p>{tags.join(', ')}</p>
</div>
);
}The same applies to objects. Use spread to create a new object with the changed fields, and use map, filter, and slice rather than push, splice, and sort on state arrays.
| Mutates in place (avoid on props and state) | Returns a new array (use instead) |
|---|---|
| `push`, `unshift` | `[...arr, x]`, `[x, ...arr]` |
| `pop`, `shift`, `splice` | `filter`, `slice` |
| `sort`, `reverse` | `[...arr].sort()`, `[...arr].reverse()` |
| `arr[i] = x` | `map` |
Where side effects belong
Real apps need side effects: updating the document title, fetching data, starting subscriptions. They just must not happen while rendering. React provides two places for them.
- Event handlers. Code that runs in response to a click or input. Handlers are not part of rendering, so they may change things freely. This is the best place for a side effect caused by a user action.
- Effects (
useEffect). Code that runs after React has rendered and updated the screen. Use it for side effects that are not caused by a single event, such as synchronizing with an external system.
import { useState } from 'react';
function SaveButton({ draft }) {
const [saved, setSaved] = useState(false);
function handleClick() {
localStorage.setItem('draft', draft); // Side effect in a handler: fine
setSaved(true);
}
return (
<button onClick={handleClick}>
{saved ? 'Saved' : 'Save draft'}
</button>
);
}The render body only reads saved and draft. The write to localStorage happens when the user clicks.
Finding impurity with Strict Mode
Wrap your app in StrictMode during development.
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>
);Strict Mode runs each component body twice and discards one result. A pure component is unaffected. Symptoms of impurity include counters that jump by two, lists that duplicate entries, and values that change between the two passes. It has no effect in production builds.
Common mistakes
- Counting renders in a module variable. The number of renders is not something your UI should depend on.
- Using
Math.random()forkeyvalues. A new key each render makes React treat each item as new, which destroys and recreates it. Use a stable id from your data. - Reading and writing a ref during render. Refs are meant for event handlers and effects. Reading
ref.currentwhile rendering makes the output depend on something React does not track. - Fetching in the render body. The request fires on every render, including the discarded ones.
- Sorting a prop in place. Copy the array first.
A quick test for any line in a render body: if the component ran twice in a row, would the second run change anything the first run left behind? If yes, move that line into a handler or an effect.
Summary of the rules
| Question | Pure answer |
|---|---|
| Can render read props, state, and context? | Yes |
| Can render create and mutate its own local variables? | Yes |
| Can render change variables that exist outside it? | No |
| Can render change props or state objects directly? | No |
| Where do side effects go? | Event handlers or effects |
Exercise
This component numbers its rows, but in Strict Mode the numbers show 2, 4, 6 instead of 1, 2, 3. Explain why, and rewrite it so it is pure. let row = 0; function Row({ text }) { row = row + 1; return <li>{row}. {text}</li>; } function Rows({ items }) { return <ul>{items.map((t) => <Row key={t} text={t} />)}</ul>; }
Show answer
Row changes the module-level variable row during render. Strict Mode calls each Row twice, so the counter advances twice per row, and the result depends on how many times React has rendered, not on the props. Pass the number in as a prop, computed from the array index in the parent: function Row({ number, text }) { return <li>{number}. {text}</li>; } function Rows({ items }) { return ( <ul> {items.map((t, i) => ( <Row key={t} number={i + 1} text={t} /> ))} </ul> ); }
Exercise
A component holds const [todos, setTodos] = useState([]). A handler does todos.push(newTodo); setTodos(todos);. The list on screen does not update. Why, and what is the fix?
Show answer
push mutates the existing array, and setTodos receives the same reference. React compares the old and new state by reference, sees no change, and skips the re-render. Create a new array instead: setTodos([...todos, newTodo]).
Exercise
Which of these are allowed in the render body of a component? (a) building a local array with push, (b) calling localStorage.setItem, (c) sorting a copy of a prop with [...items].sort(), (d) incrementing a module-level counter.
Show answer
(a) and (c) are allowed. The array in (a) is created during the same render, so mutating it is local. The copy in (c) leaves the prop unchanged. (b) is a side effect and belongs in an event handler or effect. (d) mutates a variable outside the component.