Sub topic 7
Toggling and Deleting Without Mutating State
This chapter assumes you can read JSX, you know useState, and you are comfortable with map, filter, and the spread syntax. The to-do list already renders from a todos array held in state. Now you will change items in that array without breaking React's change detection.
Why mutation breaks React
React decides whether to re-render by comparing the new state value to the old one with Object.is. For arrays and objects, that compares references, not contents. If you change an array in place and pass the same array to the setter, React sees the same reference and may skip the render.
// Broken: same array, same reference
function toggleTodo(id) {
const todo = todos.find((t) => t.id === id);
todo.done = !todo.done;
setTodos(todos); // React bails out, nothing updates
}The data changed, but the screen may not. Worse, it sometimes seems to work, because another state update triggers a render at the same time. That makes the bug intermittent and hard to trace.
The fix is to treat state as read-only. You build a new array, and for any item that changes, a new object. Everything that did not change keeps its old reference.
Toggling an item
Toggling flips done on one item. map returns a new array, so the array reference changes. For the matching item, you return a copy made with the spread syntax and override one field.
function toggleTodo(id) {
setTodos(todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));
}Read it in three parts:
todos.map(...)visits every item and builds a new array of the same length.t.id === id ? ... : treplaces only the matching item. Every other item is returned as is, with its original reference.{ ...t, done: !t.done }copies all properties oft, then overwritesdone. Properties listed later win over earlier ones.
The order inside the object literal matters. { done: !t.done, ...t } would copy t last and overwrite your change with the old value.
Deleting an item
Deleting keeps everything except one item. filter does exactly that and also returns a new array.
function deleteTodo(id) {
setTodos(todos.filter((t) => t.id !== id));
}You match on id, not on the array index. Indexes shift after a delete, and a handler that captured an old index can remove the wrong item. This is the same reason the previous chapter used todo.id as the key.
Wiring the handlers to `TodoItem`
The handlers live where the state lives, in the parent. TodoItem receives them as props and calls them with its own todo.id.
import { useState } from "react";
function TodoItem({ todo, onToggle, onDelete }) {
return (
<li>
<label>
<input
type="checkbox"
checked={todo.done}
onChange={() => onToggle(todo.id)}
/>
<span style={{ textDecoration: todo.done ? "line-through" : "none" }}>
{todo.title}
</span>
</label>
<button type="button" onClick={() => onDelete(todo.id)}>
Delete
</button>
</li>
);
}
export default function App() {
const [todos, setTodos] = useState([
{ id: "a", title: "Buy milk", done: false },
{ id: "b", title: "Write chapter", done: true },
]);
function toggleTodo(id) {
setTodos(todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));
}
function deleteTodo(id) {
setTodos(todos.filter((t) => t.id !== id));
}
return (
<main>
<h1>To-do</h1>
<ul>
{todos.map((todo) => (
<TodoItem
key={todo.id}
todo={todo}
onToggle={toggleTodo}
onDelete={deleteTodo}
/>
))}
</ul>
</main>
);
}The checkbox is a controlled input. Its checked value comes from todo.done, and onChange asks the parent to change that value. The input never holds its own truth.
The onClick and onChange handlers are wrapped in arrow functions, such as () => onDelete(todo.id). Writing onClick={onDelete(todo.id)} would call the function during render, which deletes the item immediately and triggers an infinite loop of renders.
Updater functions for safer updates
The handlers above read todos from the render in which they were created. That is a snapshot. If two updates run in the same event, the second one starts from the same stale snapshot and overwrites the first.
function completeAll() {
setTodos(todos.map((t) => ({ ...t, done: true })));
setTodos(todos.filter((t) => !t.done)); // uses the old snapshot, ignores the line above
}When the new state depends on the previous state, pass an updater function. React queues it and calls it with the latest value.
function toggleTodo(id) {
setTodos((prev) =>
prev.map((t) => (t.id === id ? { ...t, done: !t.done } : t))
);
}
function deleteTodo(id) {
setTodos((prev) => prev.filter((t) => t.id !== id));
}For a single click handler, the direct form works. The updater form is the safer default. It also keeps handlers correct if you later call them from timers, effects, or several places in one event.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| `todo.done = !todo.done` then `setTodos(todos)` | Same reference, render may be skipped | Return a copy with `{ ...t, done: !t.done }` |
| `todos.splice(i, 1)` then `setTodos(todos)` | `splice` mutates the original array | Use `filter` |
| `todos.push(x)` then `setTodos(todos)` | `push` mutates and returns a length | Use `[...todos, x]` |
| `setTodos(todos.sort(...))` | `sort` mutates and returns the same array | Copy first: `[...todos].sort(...)` or `toSorted` |
| `onClick={onDelete(id)}` | Handler runs during render | Use `onClick={() => onDelete(id)}` |
| Deleting by index | Wrong item removed after the list changes | Delete by `id` |
Why this pays off
Immutable updates cost little. Only the changed item and the array are new, and unchanged items keep their references. That helps in several ways:
- React can tell what changed by comparing references.
- A component wrapped in
React.memocan skip rendering when itstodoprop is the same object as before. - Debugging tools and undo features can keep old snapshots, because they were never altered.
Check your understanding
Exercise
A teammate writes function toggleTodo(id) { const t = todos.find((x) => x.id === id); t.done = !t.done; setTodos([...todos]); }. The screen updates, so is the code correct? Explain, and rewrite it.
Show answer
It is still wrong. [...todos] gives a new array, so React re-renders, but the item object t was mutated in place and is shared with the old array. Any memoized TodoItem receiving that same todo reference sees no change and may skip rendering, and old snapshots are altered too. Rewrite: setTodos((prev) => prev.map((x) => (x.id === id ? { ...x, done: !x.done } : x)));
Exercise
Add a "Clear completed" button to App. Write the handler so it removes every finished to-do without mutating state.
Show answer
function clearCompleted() { setTodos((prev) => prev.filter((t) => !t.done)); } Then render <button type="button" onClick={clearCompleted}>Clear completed</button>. filter returns a new array that keeps only items where done is false.