Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 2.6 — Props Are Read-Only: Keeping Components Pure
React · Example 3 of 3

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.

01

Make this component pure: ``jsx let total = 0; function Price({ amount }) { total = total + amount; return <p>Running total: {total}</p>; }

02

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

01

What makes a function pure, and why does React require components to be pure?

02

Why does StrictMode render components twice, and does that happen in production?

03

Is const list = []; list.push(x); inside a component allowed? Is props.list.push(x)? Why?

04

Where should side effects go if not in render?

Mutating a prop changes the parent's data

Preview

Press Run to see the page.

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 ]