Sub topic 13
Updating Objects Inside Arrays
This chapter assumes you can update a nested object with spread, and that you know map and useState. It combines the two. State often holds an array of objects, such as todos, cart lines, or users. Changing one field on one of those objects takes more care than either pattern alone.
A new array is not enough
Copying the array does not copy the objects inside it. The spread operator makes a shallow copy, so the new array holds the same object references as the old one.
function handleToggle(id) {
const next = [...todos];
const todo = next.find((t) => t.id === id);
todo.done = !todo.done; // Wrong: this object is shared with the old array
setTodos(next);
}The todo object is still the one from the current snapshot, and the code just changed it in place. React gets a new array, so it re-renders. But the previous state was mutated, and any child component that compares props by reference may skip the update.
Copy every level on the path
Replace each level between the array and the changed value: the array, then the object, then any nested object. Leave everything else as it is. map does this, because it returns a new array and lets you return either a new object or the original one for each item.
A complete example
This component changes a priority stored in a nested object. The path is array, item, meta.
import { useState } from 'react';
const initialTodos = [
{ id: 0, title: 'Buy milk', meta: { priority: 'low' } },
{ id: 1, title: 'Write report', meta: { priority: 'high' } },
];
export default function TodoList() {
const [todos, setTodos] = useState(initialTodos);
function handlePriorityChange(id, priority) {
setTodos(
todos.map((todo) =>
todo.id === id
? { ...todo, meta: { ...todo.meta, priority } }
: todo
)
);
}
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>
{todo.title}{' '}
<select
value={todo.meta.priority}
onChange={(e) => handlePriorityChange(todo.id, e.target.value)}
>
<option value="low">low</option>
<option value="high">high</option>
</select>
</li>
))}
</ul>
);
}Read the ternary as a rule: if this is the target item, return a modified copy, otherwise return the original object untouched.
Common errors
- Mutating inside
map, for exampletodo.done = true; return todo;. The array is new, but the object is the old one. - Copying only the top of the path.
{ ...todo, meta: { priority } }drops any other fields inmeta. Spreadtodo.metatoo. - Using the index as the target when the list can be reordered. Match on a stable
idinstead. - Forgetting the
elsebranch, somapreturnsundefinedfor the other items.
When the path gets three or four levels deep, the spread code becomes hard to read. Two later options help. You can keep state flat, or you can write the update with Immer.
Exercise
A cart is stored as [{ id: 1, name: 'Pen', qty: 1 }, ...]. Write the setter call that increases qty by 1 for the item with a given id, without mutating any object.
Show answer
setCart(cart.map((item) => item.id === id ? { ...item, qty: item.qty + 1 } : item));