Sub topic 10
Changing Items with map
This chapter covers map as the standard way to replace or change items in an array held in React state. It assumes you know JavaScript objects and arrays, map, filter, and slice, and the basics of function components, useState, and event handlers. Earlier chapters covered adding items with spread and removing them with filter. Here you will change items that are already in the array.
Why you can't assign into the array
Suppose you want to mark one todo as done. The direct approach is to find the item and edit it:
// Wrong: mutates the array held in state
todos[1].done = true;
setTodos(todos);This breaks for the reason covered in the chapter on why mutation fails. setTodos receives the same array reference that state already holds. React compares the old and new values with Object.is, sees the same reference, and can skip the re-render. Even when something else triggers a render, the change bypassed React's tracking, so the result is hard to predict.
The fix follows the same rule as for objects: build a new array and pass that to the setter. For changes to existing items, map does this.
How map fits state updates
map calls a function on every item and returns a new array of the results. It never changes the original array. That makes it a non-mutating method, so you can safely call it on state.
The callback decides what each position in the new array holds. For items you want to keep, return the original item. For the item you want to change, return a changed copy.
let nextId = 0;
const [todos, setTodos] = useState([]);
function toggleTodo(id) {
setTodos(todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));
}Read the callback in two parts:
t.id === id ? ... : tis a condition. When the id does not match, the callback returnst, the same object that was already in the array.{ ...t, done: !t.done }runs only for the matching item. It copies every property oftinto a new object, then overridesdone.
The result is a new array. Most of its items are the same objects as before. One item is a new object.
Walking through one update
Take this state:
const todos = [
{ id: 0, title: 'Buy milk', done: false },
{ id: 1, title: 'Write chapter', done: false },
{ id: 2, title: 'Walk dog', done: true },
];Calling toggleTodo(1) runs the callback three times:
| Index | `t.id === 1` | Callback returns |
|---|---|---|
| 0 | false | the original object for "Buy milk" |
| 1 | true | a new object: `{ id: 1, title: 'Write chapter', done: true }` |
| 2 | false | the original object for "Walk dog" |
The new array has a new reference, so React re-renders. The objects at index 0 and 2 are shared between the old and new arrays. That is safe as long as you never mutate them, and it is cheap, because only one object was copied.
Replacing an item with a different value
You do not have to produce a copy of the old item. Sometimes you want to replace the item outright. State that holds an array of numbers is the simplest case. Here, clicking a button increments the counter at one position:
import { useState } from 'react';
export default function CounterList() {
const [counters, setCounters] = useState([0, 0, 0]);
function handleIncrement(index) {
setCounters(
counters.map((c, i) => (i === index ? c + 1 : c))
);
}
return (
<ul>
{counters.map((c, i) => (
<li key={i}>
{c} <button onClick={() => handleIncrement(i)}>+1</button>
</li>
))}
</ul>
);
}The second callback argument, i, is the index. Numbers are primitives, so there is nothing to copy. You return a different number for one position and the original number for the rest. The same shape works for any value type.
The index key in this example is acceptable only because the list never reorders, inserts, or deletes. For lists that do, use stable ids, as the todo examples do.
Choosing what to match on
Match on a stable id when items have one. Match on the index only when the position itself is what the user chose, as in the counters above. Index matching goes wrong when the list can change between rendering and the click, for example after a sort. An id still points at the same logical item.
Changing several items at once
Because map visits every item, one pass can update many. This marks every todo done:
setTodos(todos.map((t) => ({ ...t, done: true })));This one changes only the todos whose titles are in a set:
const selected = new Set(['Buy milk', 'Walk dog']);
setTodos(
todos.map((t) => (selected.has(t.title) ? { ...t, done: true } : t))
);Returning the original t for non-matches matters here. If you return { ...t } for every item, you create a new object for each item. The result still works, but every item looks changed to code that compares references, such as React.memo or effect dependencies.
Common errors
Mutating inside the callback
The callback can mutate the item and return it. This looks like it works and is wrong:
// Wrong: mutates the object that is still inside the old array
setTodos(
todos.map((t) => {
if (t.id === id) {
t.done = !t.done;
}
return t;
})
);map returns a new array here, so React does re-render. But the matched item is the same object as before, mutated in place. The old snapshot was altered. Anything that depends on that object's identity, such as React.memo on a Todo component, sees no change and skips the update. In Strict Mode, React also double-invokes some functions to expose this kind of impurity, and you can get doubled results.
Forgetting the else branch
// Wrong: non-matching items become undefined
setTodos(todos.map((t) => t.id === id && { ...t, done: true }));When the condition is false, the callback returns false, so the array fills with false values and the render fails or shows nothing. Always return the original item for the non-matching case.
Using forEach or a loop to build the result
forEach returns undefined. Assigning its result to state replaces your array with undefined. Use map when you want a new array of the same length. Use filter when you want fewer items.
Copying only part of a nested change
When the changed value is inside an item, copy each level on the path. This changes a nested field of one item:
function renameCity(id, city) {
setPeople(
people.map((p) =>
p.id === id ? { ...p, address: { ...p.address, city } } : p
)
);
}Writing { ...p, address: p.address } and then assigning address.city would mutate the shared nested object. The spread only copies one level, so you must copy address as well.
Combining map with an updater function
When several updates may be queued in one event, use the updater form so each one sees the latest state:
function markAllDoneThenRename(id, title) {
setTodos((prev) => prev.map((t) => ({ ...t, done: true })));
setTodos((prev) => prev.map((t) => (t.id === id ? { ...t, title } : t)));
}With the plain form, both calls would start from the same todos snapshot, and the second would overwrite the first. With updaters, the second receives the result of the first. The map logic is unchanged. Only the source of the array differs.
When map is the wrong tool
- To add an item, use spread:
[...todos, newTodo]. - To remove an item, use
filter. - To insert at a position, use
sliceon both sides of the position. - To change only one deeply nested value in a large structure,
mapat each level gets verbose. Flatter state or Immer, covered in later chapters, handles that better.
Also note the cost. map visits every item even when you change one. For lists of a few thousand items this is negligible. For very large lists updated on every keystroke, consider whether the state should be split up or flattened.
Exercise
A component holds const [items, setItems] = useState([{ id: 1, qty: 1 }, { id: 2, qty: 5 }]). Write a handler increaseQty(id) that adds 1 to the qty of the item with that id without mutating state. Then explain why items.map((i) => { if (i.id === id) i.qty += 1; return i; }) is wrong even though it returns a new array.
Show answer
function increaseQty(id) { setItems(items.map((i) => (i.id === id ? { ...i, qty: i.qty + 1 } : i))); }. The second version creates a new outer array but mutates the existing item object in place. The old snapshot is altered, and any code that compares item references (such as React.memo or effect dependencies) sees the same object and may skip updating.
Exercise
What does this call put in state when no todo matches the id, and why does it break rendering? setTodos(todos.map((t) => t.id === id && { ...t, done: true }))
Show answer
Every non-matching item becomes false, because t.id === id && ... evaluates to false when the comparison fails. The array then contains false values instead of todo objects, so code that reads t.title or t.id fails or renders nothing. Fix it with a ternary that returns t for non-matches: t.id === id ? { ...t, done: true } : t.