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 2 of 3

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.

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?

The pure version survives the double render

Preview

Press Run to see the page.

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' ]