Sub topic 10
Changing items with map
This chapter assumes you know JavaScript arrays and objects, the spread operator, map and filter, and basic useState usage with event handlers in function components.
The problem
You have a list in state and want to change one item. Calling todo.done = true mutates the existing object. React compares the old and new state by reference, so it sees no change and may skip the re-render. Even when the screen happens to update, the old snapshot is corrupted.
The fix is to build a new array in which the changed item is replaced by an updated copy. The map method does this. It returns a new array and leaves the original untouched.
The pattern
map runs a function on every item and collects the results. To change one item, return a modified copy for the matching item and return every other item as is.
import { useState } from 'react';
export default function TodoList() {
const [todos, setTodos] = useState([
{ id: 1, title: 'Write chapter', done: false },
{ id: 2, title: 'Review code', done: false },
{ id: 3, title: 'Ship it', done: false },
]);
function toggleTodo(id) {
setTodos(
todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t))
);
}
return (
<ul>
{todos.map((t) => (
<li key={t.id}>
<label>
<input
type="checkbox"
checked={t.done}
onChange={() => toggleTodo(t.id)}
/>
{t.title}
</label>
</li>
))}
</ul>
);
}Three things happen in toggleTodo:
mapcreates a new array, so the array reference changes.- For the matching item,
{ ...t, done: !t.done }creates a new object withdoneflipped. - Every other item is returned unchanged. Those objects keep their identity, so React can skip work for them if they are memoized.
Changing several items
The same shape works when many items change. Put the condition in the callback and return a copy only for the items that need it.
function markAllDone() {
setTodos(todos.map((t) => (t.done ? t : { ...t, done: true })));
}Items already done are returned as they are, so only the changed items get new objects.
Common errors
- Mutating inside
map. Writingt.done = !t.done; return t;returns the same object, so you mutate state even thoughmapmade a new array. - Forgetting the
elsebranch. If the callback returns nothing for non-matching items, those items becomeundefined. - Using
forEachorsplicefor the update. These do not return a new array, andsplicemutates. - Using the index when the list can change order. Match on a stable
idinstead. - Shallow copy of a nested value.
{ ...t, done: true }copies only the top level. If the item contains a nested object you want to change, copy that too:
setTodos(
todos.map((t) =>
t.id === id ? { ...t, meta: { ...t.meta, edited: true } } : t
)
);Replacing the whole item
You do not have to spread. If you have a complete new value, such as an edited todo from a form, return it directly for the matching id.
function replaceTodo(nextTodo) {
setTodos(todos.map((t) => (t.id === nextTodo.id ? nextTodo : t)));
}Exercise
A teammate writes setTodos(todos.map((t) => { if (t.id === id) { t.done = true; } return t; }));. Why is this wrong, and how would you fix it?
Show answer
The map call returns a new array, but the matching item is the same object that was mutated with t.done = true. This changes the previous snapshot and breaks the rule that state is read-only. Return a copy instead: setTodos(todos.map((t) => (t.id === id ? { ...t, done: true } : t)));.
Exercise
Write a function renameItem(id, title) that updates only the title of the item with the matching id in a items state array, without mutating any object.
Show answer
function renameItem(id, title) { setItems(items.map((item) => (item.id === id ? { ...item, title } : item))); }