Skip to content
ClapelloNotes by Barath
ReactCh 05 · 4/6
Core4 min readUpdated

React / 25

Updating objects and arrays in state

TL;DR

Never change state in place. Build a new object or array with the change and set that, so React sees a new value and re-renders.

How React compares

Mutate

your code

cart.push(item); setCart(cart);
same array, new contents

react checks

Object.is(old, new) → true

result · bug

Nothing changed? Skip the render.

Copy

your code

setCart([...cart, item]);
a brand-new array

react checks

Object.is(old, new) → false

result

Changed. Render with the new list.

React compares the old and new value with Object.is. For objects and arrays that checks the reference (which box), not what's inside it.

React uses Object.is(oldValue, newValue). For numbers and strings, that compares the values. For objects and arrays, it compares references: is this the same object in memory? Changing what's inside doesn't make a new object.

So the rule: treat objects and arrays in state as read-only. To change one, make a new one.

Objects: spread and override

const [user, setUser] = useState({ name: "Asha", city: "Chennai" });
 
setUser({ ...user, city: "Pune" }); // new object: name copied, city replaced

...user copies every field into a new object, and fields listed after it win. Spread is shallow, so nested objects need their own spread:

setUser({ ...user, address: { ...user.address, pin: "411001" } });

Arrays: the cheat sheet

ToAvoid (changes the array)Use (returns a new array)
addpush, unshift[...arr, x], [x, ...arr]
removesplice, pop, shiftfilter
change an itemarr[i] = xmap
sort / reversesort, reversetoSorted, toReversed, or copy first: [...arr].sort()

Example: a cart

Cart.jsx
const [cart, setCart] = useState([]);
 
function addItem(dish) {
  setCart((c) => [...c, { id: dish.id, name: dish.name, qty: 1 }]);
}
 
function removeItem(id) {
  setCart((c) => c.filter((item) => item.id !== id));
}
 
function increase(id) {
  setCart((c) =>
    c.map((item) => (item.id === id ? { ...item, qty: item.qty + 1 } : item))
  );
}

Each function builds a new array. increase also builds a new object for the one item that changed, and reuses the others untouched. Using updaters (c => …) keeps them correct even when called several times in a row.

Don't

Mutate, then set

function increase(id) {
  const item = cart.find((i) => i.id === id);
  item.qty += 1;     // changes the existing object
  setCart(cart);     // same array: no re-render
}

Do

Copy the path to the change

function increase(id) {
  setCart((c) =>
    c.map((i) => (i.id === id ? { ...i, qty: i.qty + 1 } : i))
  );
}

Why React works this way

Comparing references is instant, while comparing every field of every object would be slow. Immutable updates also make other things cheap and safe: skipping work in memoised components, undo/redo, and the old snapshot staying correct for code that still holds it.

Gotchas

Recall

Can you answer these?

0/4

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.