Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.6 — Updating Objects in State
React · Example 1 of 3

Mutating does nothing; a new object re-renders

Mutate changed the object but caused no render, so the dot stayed put. Copy then made a new object from the mutated one (10 + 10), so the dot jumps to 20: the hidden mutation leaked into the next state. Mutation bugs often show up later, somewhere else.

Treat objects in state as read-only: to change one, create a new object (usually with spread { ...obj, field: value }, copying every level you change in nested objects) and pass it to the setter, because React detects changes by comparing references.

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

State is { name: "Asha", settings: { theme: "light", fontSize: 16 } }. Write a handler that switches the theme to dark without mutating.

02

Write a Score component with state { player: "Ravi", points: 0 } and a button that adds 5 points with an updater function.

Explain it without notes

01

Why doesn't position.x = 5; setPosition(position) re-render?

02

How do you update one field of an object in state? And one field of a nested object?

03

What does "spread is shallow" mean, and why does it matter?

04

What does Immer do, and when would you use it?

Mutating does nothing; a new object re-renders

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

render: x = 0
mutated: the object now says x = 10
render: x = 20