Sub topic 14
Keeping components pure
This chapter assumes you can write function components, pass props, and use useState. It also assumes you know how to copy arrays with spread syntax and map.
What pure means
A pure component follows two rules:
- Given the same props, state, and context, it returns the same JSX.
- It does not change anything that existed before it started rendering.
React depends on these rules. It can call your component more than once, skip a render, or discard one and start again. In development, Strict Mode calls each component twice on purpose so that impure code shows up as a visible bug.
Mutating a variable outside the component
This component changes a variable that lives outside it:
let guestCount = 0;
function Cup() {
guestCount = guestCount + 1;
return <h2>Cup for guest #{guestCount}</h2>;
}
export default function Table() {
return (
<>
<Cup />
<Cup />
<Cup />
</>
);
}The output depends on how many times React has called Cup, not on its inputs. Under Strict Mode the guests are numbered 2, 4, and 6. Pass the value in as a prop instead:
function Cup({ guest }) {
return <h2>Cup for guest #{guest}</h2>;
}
export default function Table() {
return (
<>
<Cup guest={1} />
<Cup guest={2} />
<Cup guest={3} />
</>
);
}Calling Math.random() or Date.now() during render breaks the first rule in the same way. The same props produce different output on each call.
Mutating props and state
Props are read-only. Methods such as push, splice, and sort change an array in place, so calling them on a prop changes the parent's data:
function SortedList({ items }) {
const sorted = [...items].sort();
return (
<ul>
{sorted.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
}Writing items.sort() would reorder the parent's array during render. The copy [...items] avoids that. The same rule applies to state: call the setter with a new array or object. Do not modify the old one.
Where side effects belong
Apps still need to change things: update the page title, send a request, or start a timer. These changes are called side effects. Keep them out of the render body:
- Put effects caused by user actions in event handlers. A handler is not part of rendering, so it does not need to be pure.
- Put effects that must run because the component appeared on screen in
useEffect. A later chapter covers it.
import { useState } from 'react';
function Subscribe() {
const [email, setEmail] = useState('');
function handleSubmit(event) {
event.preventDefault();
console.log('Subscribing', email);
}
return (
<form onSubmit={handleSubmit}>
<input value={email} onChange={(e) => setEmail(e.target.value)} />
<button type="submit">Subscribe</button>
</form>
);
}The console.log lives in handleSubmit, so it runs once per submit, not once per render.
Common errors
| Symptom | Likely cause |
|---|---|
| Values count twice in development | Render changes a module-level variable |
| Parent list reorders unexpectedly | Child calls `sort` or `reverse` on a prop |
| Output differs on every render | Render uses `Math.random()` or `Date.now()` |
| UI does not update after a state change | State was mutated in place, not replaced |
Exercise
A component receives scores as a prop and renders scores.reverse().map(...). Why is this impure, and how do you fix it?
Show answer
reverse changes the array in place, so rendering alters the parent's data and gives different results on repeated renders. Copy first: [...scores].reverse().map(...).