StrictMode exposes an impure component
This example uses StrictMode on purpose (most examples on Hectal leave it out). StrictMode called each Cup twice, so the outside counter rose by two each time and the cups show #2, #4 and #6. Remove <StrictMode> and you'd see #1, #2, #3: the bug hides, but it's still there.
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
[ 'Tea cup for guest #2', 'Tea cup for guest #4', 'Tea cup for guest #6' ]