Sub topic 14
Adding, removing, and changing items in state
This chapter assumes you know useState, map, filter, and the spread operator. It covers how to update an array held in state without changing the original array.
Why updates must be immutable
React compares the new state value with the old one. If you change an array in place and pass the same array to the setter, React sees the same reference and may skip the re-render. Methods such as push, splice, and sort change the array in place. Avoid them on state.
Instead, build a new array from the old one. Three tools cover most cases:
| Goal | Use | Avoid |
|---|---|---|
| Add | `[...items, newItem]` | `push`, `unshift` |
| Remove | `items.filter(...)` | `splice`, `pop` |
| Change | `items.map(...)` | `items[i] = ...` |
Adding an item
Spread the old items into a new array, then add the new one. Give each new item a unique id so it can serve as a key.
import { useState } from 'react';
let nextId = 3;
function Tasks() {
const [tasks, setTasks] = useState([
{ id: 1, title: 'Write chapter', done: false },
{ id: 2, title: 'Review code', done: true },
]);
const [title, setTitle] = useState('');
function add() {
if (title.trim() === '') return;
setTasks([...tasks, { id: nextId++, title, done: false }]);
setTitle('');
}
function remove(id) {
setTasks(tasks.filter(task => task.id !== id));
}
function toggle(id) {
setTasks(
tasks.map(task =>
task.id === id ? { ...task, done: !task.done } : task
)
);
}
return (
<>
<input value={title} onChange={e => setTitle(e.target.value)} />
<button onClick={add}>Add</button>
{tasks.length === 0 ? (
<p>No tasks yet.</p>
) : (
<ul>
{tasks.map(task => (
<li key={task.id}>
<input
type="checkbox"
checked={task.done}
onChange={() => toggle(task.id)}
/>
{task.title}
<button onClick={() => remove(task.id)}>Remove</button>
</li>
))}
</ul>
)}
</>
);
}Do not use the array index as the id for new items. Indexes shift when items are removed, which breaks the key rules from earlier in this tutorial.
Removing an item
filter returns a new array that holds only the items for which the callback returns true. To remove an item, keep every item whose id does not match:
setTasks(tasks.filter(task => task.id !== id));Changing an item
Use map to return a new array. For the matching item, return a copy with the changed field. For all others, return the original object.
setTasks(
tasks.map(task =>
task.id === id ? { ...task, done: !task.done } : task
)
);The copy matters. Writing task.done = !task.done changes the object that the old array also points to. That is still a mutation, even though map created a new array.
Common errors
- Calling
tasks.push(item)and thensetTasks(tasks). The reference is unchanged, so the update may not appear. - Calling
tasks.sort()on state.sortreorders in place. Copy first with[...tasks].sort(...). - Using several updates in a row in one handler, such as calling
setTasks([...tasks, a])and thensetTasks([...tasks, b]). Both calls read the sametasksvalue from that render, so onlybis added. Use the updater form instead:setTasks(prev => [...prev, a]), thensetTasks(prev => [...prev, b]).
Exercise
A handler runs const copy = tasks; copy.push(newTask); setTasks(copy);. Why can this fail to update the screen, and what is a correct one-line replacement?
Show answer
copy is not a copy. It points to the same array as tasks, and push changes that array in place. React then receives the same reference and may skip the re-render. A correct replacement is setTasks([...tasks, newTask]);.
Exercise
Write the setTasks call that renames the task with a given id to a new title, without mutating any task.
Show answer
setTasks(tasks.map(task => task.id === id ? { ...task, title } : task));