Replacing, Not Editing

The rule. Never change an object or array that is in state. Make a new one.

Why. React decides whether to re-render by asking whether the new value is the same value as the old one. Editing an array in place leaves it the same array, so React sees nothing to do and the screen does not update, even though the data really did change.

Adding an item

Mutating

// Nothing happens on screen.
// Same array, so React sees no change.
items.push(newItem);
setItems(items);

Replacing

// A new array, so React re-renders.
setItems([...items, newItem]);
Compare → push, splice, sort and reverse all change the original. concat, filter, map and slice all return something new. When in doubt, check which kind you are using.

Try it

Replace setItems([...items, 'Wild Seed']) with items.push('Wild Seed') and click Add. The array really does grow, and the screen never changes.

loading editor…

loading React…

Derived values are not state. If you can calculate something from state you already have, calculate it during the render. A second piece of state holding items.length can fall out of step with items. A plain const count = items.length cannot.

◈ Graded Component

Build a counter with three controls. Render the current value inside an element with id count, starting at 0. A button with id inc adds one. A button with id dec subtracts one. A button with id reset returns it to 0. The value must never go below zero.

Checked against what your component renders and how it responds, not against how you wrote it. 3 visible and 3 hidden checks.

loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back