Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 6.2 — Derived Values: Compute, Don't Store
React · Example 3 of 3

When copying a prop is right: a starting value

Edit both boxes, then click the button. The first editor keeps your typing; the second gets a new key, so React creates a fresh editor that starts from the new draft. Topic 6.4 explains keys and resets in full.

If a value can be calculated from props or state, calculate it during render instead of storing it; copying a prop into state freezes it at its first value, which is fine only when the prop is meant as a starting value.

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

A cart component stores items and total in state and updates both in addItem. Rewrite it with only the state it needs.

02

This component shows a stale price when the parent changes price: function Price({ price }) { const [p] = useState(price); return <b>₹{p}</b>; }. Fix it.

Explain it without notes

01

What is derived state and where should you compute it?

02

Explain the "mirror props in state" bug. Why does it happen?

03

When is it correct to initialise state from a prop?

04

A filtered list of 20,000 rows is slow to compute on every keystroke. Should you store it in state? What should you do instead?

When copying a prop is right: a starting value

Preview

Press Run to see the page.

Console

Nothing logged yet.