React / 25
Updating objects and arrays in state
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);react checks
Object.is(old, new) → trueresult · bug
Nothing changed? Skip the render.
Copy
your code
setCart([...cart, item]);react checks
Object.is(old, new) → falseresult
Changed. Render with the new list.
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
| To | Avoid (changes the array) | Use (returns a new array) |
|---|---|---|
| add | push, unshift | [...arr, x], [x, ...arr] |
| remove | splice, pop, shift | filter |
| change an item | arr[i] = x | map |
| sort / reverse | sort, reverse | toSorted, toReversed, or copy first: [...arr].sort() |
Example: a cart
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.
