Sub topic 13
Updating objects inside arrays
This chapter assumes you know JavaScript objects, arrays, spread syntax, and the array methods map, filter, and slice. It also assumes you can write a React function component that uses useState and handles events. Earlier chapters covered updating a nested object and changing array items with map. Here you combine the two: state that holds an array of objects, where one object contains nested data.
The problem
A list of objects is the most common shape of state in real apps. Todos, cart lines, and form rows all look like this. Each item in the array is an object, and an update usually targets one property of one item.
Two facts from earlier chapters apply at once:
- You must not mutate the array. Methods such as
push,splice, andsortchange it in place. - Spread makes a shallow copy. Copying an array copies the references to its objects. It does not copy the objects.
The second fact is the source of most bugs in this area. After const next = [...todos], next is a new array, but next[0] and todos[0] are the same object. If you then write next[0].done = true, you have changed the object that the current snapshot of state still points to.
Why a copied array is not enough
Consider this handler:
function toggleTodo(id) {
const next = [...todos];
const todo = next.find((t) => t.id === id);
todo.done = !todo.done; // Wrong: mutates an object that state still holds
setTodos(next);
}Here React does get a new array, so the component re-renders. The code looks like it works. The mutation is still a bug:
- The previous snapshot of
todosis now corrupted. Any code that closed over it sees the changed value. - Child components wrapped in
React.memoreceive the same object reference as before. They compare it with the old one, find no difference, and skip rendering. The changed item may not appear on screen. - Features that depend on comparing old and new state, such as undo history, break because the old state was edited.
The rule is to copy every object on the path from the root of the state to the value you change. Objects off that path keep their old identity and can be reused.
The standard pattern: map and spread
map already returns a new array. Inside the callback, return the original item when it should not change, and return a copy with the change when it should.
import { useState } from 'react';
let nextId = 3;
export default function TodoList() {
const [todos, setTodos] = useState([
{ id: 0, title: 'Write chapter', done: false },
{ id: 1, title: 'Review draft', done: true },
{ id: 2, title: 'Publish', done: false },
]);
function toggleTodo(id) {
setTodos(
todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t))
);
}
function renameTodo(id, title) {
setTodos(
todos.map((t) => (t.id === id ? { ...t, title } : t))
);
}
return (
<ul>
{todos.map((t) => (
<li key={t.id}>
<input
type="checkbox"
checked={t.done}
onChange={() => toggleTodo(t.id)}
/>
<input
value={t.title}
onChange={(e) => renameTodo(t.id, e.target.value)}
/>
</li>
))}
</ul>
);
}Three details matter:
- The match uses
id, not the array index. Indexes shift when items are added, removed, or sorted, so an id is a stable way to name an item. { ...t, done: !t.done }copies the matching item and overrides one property. The properties you do not name are carried over.- Every other item is returned as the same reference. Unchanged items keep their identity, which is what lets memoized children skip work.
Objects nested inside the items
Sometimes the object you change sits one level deeper than the item. Suppose each todo has a meta object:
const [todos, setTodos] = useState([
{ id: 0, title: 'Write chapter', meta: { priority: 'low', tags: ['docs'] } },
{ id: 1, title: 'Review draft', meta: { priority: 'high', tags: [] } },
]);
function setPriority(id, priority) {
setTodos(
todos.map((t) =>
t.id === id
? { ...t, meta: { ...t.meta, priority } }
: t
)
);
}The path from the root to the changed value is: the array, then the todo, then meta, then priority. Each of the first three gets a fresh copy: map makes the array, { ...t } makes the todo, and { ...t.meta } makes meta. The value priority is a string, so it is replaced rather than copied.
The sibling todo (id: 1) and the tags array of the changed todo are not on the path. Both keep their original references.
Nested arrays inside an item
The same idea applies when the nested value is an array. To add a tag to one todo, copy the array, the todo, and the tags array:
function addTag(id, tag) {
setTodos(
todos.map((t) =>
t.id === id
? { ...t, meta: { ...t.meta, tags: [...t.meta.tags, tag] } }
: t
)
);
}
function removeTag(id, tag) {
setTodos(
todos.map((t) =>
t.id === id
? { ...t, meta: { ...t.meta, tags: t.meta.tags.filter((x) => x !== tag) } }
: t
)
);
}These lines show why deep state becomes painful. Each level adds a layer of spread, and a missed layer silently mutates something. The next sections cover two ways to reduce that cost.
Updating more than one item
map can apply the same rule to many items. This marks every todo as done:
function completeAll() {
setTodos(todos.map((t) => ({ ...t, done: true })));
}It can also apply a condition. This marks only the todos that carry a given tag:
function completeTagged(tag) {
setTodos(
todos.map((t) =>
t.meta.tags.includes(tag) ? { ...t, done: true } : t
)
);
}If nothing matches, map still returns a new array, so React re-renders even though no item changed. This is harmless for small lists. For large ones you can check first and call the setter only when something would change.
Use an updater function when updates stack up
The handlers above read todos from the current render. That is correct for a single update per event. If one event runs several updates, or an update runs later (in a timeout or after a fetch), the todos variable may be stale. Pass a function to the setter and let React supply the latest value:
function toggleTodo(id) {
setTodos((prev) =>
prev.map((t) => (t.id === id ? { ...t, done: !t.done } : t))
);
}
function toggleTwice(id) {
toggleTodo(id);
toggleTodo(id);
}With the plain form, both calls in toggleTwice would start from the same snapshot and the second would overwrite the first, so the todo would end up toggled once. With updater functions, React queues them and passes each one the result of the previous, so the todo ends up back where it started.
Keep updater functions pure. They must not mutate prev and must not cause side effects. In development, React calls them twice to expose mistakes, so a mutation inside one produces visible double effects.
Keep the list flat when you can
If you often update items at depth three or four, consider changing the shape of the state. Instead of storing tags inside each todo's meta, keep a separate array that refers to todos by id:
const [todos, setTodos] = useState([
{ id: 0, title: 'Write chapter', priority: 'low' },
]);
const [tags, setTags] = useState([
{ todoId: 0, label: 'docs' },
]);
function addTag(todoId, label) {
setTags([...tags, { todoId, label }]);
}Adding a tag is now a one-level update. The trade-off is that you join the data when you render, for example with tags.filter((g) => g.todoId === t.id). Flat state suits data that is edited on its own, while nested state suits data that is always read and replaced as one unit.
Immer for deeply nested updates
Immer lets you write the update as if you were mutating, against a temporary draft. It produces the immutable copy for you. With use-immer:
import { useImmer } from 'use-immer';
const [todos, updateTodos] = useImmer([
{ id: 0, title: 'Write chapter', meta: { priority: 'low', tags: ['docs'] } },
]);
function addTag(id, tag) {
updateTodos((draft) => {
const todo = draft.find((t) => t.id === id);
todo.meta.tags.push(tag);
});
}Here push and the property assignments act on the draft, not on your real state. Immer tracks which parts changed and copies only those, so unchanged items keep their references, as in the hand-written version.
Immer has its own gotchas:
- Write inside the callback. Mutating the object outside it still mutates real state.
- Either mutate the draft or return a new value from the callback, but not both.
- It adds a dependency. For a single level of nesting,
mapand spread are usually shorter than the setup.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Checkbox does not update | The same array was passed back, for example after `push` | Build a new array with `map`, `filter`, or spread |
| Screen updates, but a memoized child does not | The array is new but the changed item was edited in place | Copy the item with `{ ...item, change }` |
| Editing one item changes another | Two items share one nested object after a shallow copy | Copy the nested object on the path, or give each item its own |
| Two quick updates produce one change | Both read the same stale snapshot | Use `setState((prev) => ...)` |
| Wrong item changes after sorting or deleting | Matching by array index | Match by a stable `id` |
Summary of the pattern
To change one property of one object in an array:
- Use
mapto build the new array. - Match the target item by
id. - Return
{ ...item, property: newValue }for the target and the original item for the rest. - For deeper values, add one spread per level on the path to the value.
- Use
setState((prev) => ...)when several updates can run before the next render, or when the update runs asynchronously.
Exercise
A component keeps const [items, setItems] = useState([{ id: 1, qty: 1, info: { color: 'red' } }, { id: 2, qty: 1, info: { color: 'blue' } }]). Write a handler setColor(id, color) that changes the color of one item without mutating state. Which objects in the new state are the same references as in the old state?
Show answer
function setColor(id, color) { setItems((prev) => prev.map((item) => item.id === id ? { ...item, info: { ...item.info, color } } : item)); }. The unchanged item (the one whose id did not match) is the same reference as before. The changed item and its info object are new copies, and so is the array.
Exercise
This handler is meant to increase the quantity of one item, but a memoized ItemRow child sometimes does not show the new value. Explain why, and fix it. function increment(id) { const next = [...items]; next.find((i) => i.id === id).qty += 1; setItems(next); }
Show answer
The spread copies only the array. The found item is the same object as before, and the code edits it in place. ItemRow receives the same object reference, so its memo check sees no change and skips rendering. The fix is setItems(items.map((i) => i.id === id ? { ...i, qty: i.qty + 1 } : i)), which gives the changed item a new reference.