Sikau

React · Day 11 · about 30 min

Updating arrays and objects

Copy, don't change: immutable updates.

I pushed, nothing happened

items.push(x) then setItems(items) — and the screen doesn't change. React compares the *old* and *new* value; it's the same array, so React thinks nothing changed. Always make a new array or object: that's immutability.

The copy patterns

const items = [{ id: 1, name: "Momo", qty: 1 }];

// add
const added = [...items, { id: 2, name: "Tea", qty: 1 }];
// remove
const removed = added.filter((i) => i.id !== 1);
// update one
const updated = added.map((i) => (i.id === 2 ? { ...i, qty: i.qty + 1 } : i));

console.log(added.length, removed.length, updated[1].qty, items.length);
  • Objects: setUser({ ...user, city: "Pokhara" }).
  • Avoid push, splice, sort() and assigning properties on state directly; toSorted() and toSpliced() return copies.
  • Use the function form when the new state depends on the old: setItems((prev) => [...prev, item]).

The rest of this lesson

  • Why React needs new objectsexplain
  • Nested updatesexplain
  • Will it re-render?predict
  • Immutable recipematch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of React