Mutating a prop changes the parent's data
The first Entered rendered before Ranked sorted the array; the second rendered after, so the same data shows two different orders on one screen. The fix is one word: items.toSorted(...) returns a new array and leaves the prop alone.
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
[ 'In the order entered: 30, 10, 20', 'Ranked: 30, 20, 10', 'In the order entered: 30, 20, 10' ]
scores is now [ 30, 20, 10 ]