The pure version survives the double render
Also in StrictMode on purpose. Every Cup still renders twice (each log line appears twice), but the screen is correct, because a pure component gives the same answer both times.
A React component must behave like a pure function: given the same props (and state), it returns the same JSX and changes nothing outside itself while rendering; side effects go in event handlers or effects, and StrictMode renders twice in development to catch components that break this rule.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Make this component pure:
``jsx
let total = 0;
function Price({ amount }) {
total = total + amount;
return <p>Running total: {total}</p>;
}
This component reverses its prop. Fix it so the parent's array is never changed:
``jsx
function Newest({ posts }) {
return <ul>{posts.reverse().map((p) => <li key={p}>{p}</li>)}</ul>;
}
Explain it without notes
What makes a function pure, and why does React require components to be pure?
Why does StrictMode render components twice, and does that happen in production?
Is const list = []; list.push(x); inside a component allowed? Is props.list.push(x)? Why?
Where should side effects go if not in render?
Preview
Console
Nothing logged yet.Expected console output
render Cup 1
render Cup 1
render Cup 2
render Cup 2
render Cup 3
render Cup 3
[ 'Tea cup for guest #1', 'Tea cup for guest #2', 'Tea cup for guest #3' ]