Sub topic 8
Adding to an Array
This chapter assumes you know JavaScript arrays and the spread operator, and that you can write a React function component with useState and event handlers. Here you will add items to an array in state without mutating it.
Why `push` is the wrong tool
push changes the existing array. If you call todos.push(item) and then setTodos(todos), React receives the same array reference it already holds. It sees no change and may skip the render. Even when the screen does update, the previous snapshot of state has been altered, which breaks anything that compares old and new values.
The fix is to build a new array that contains the old items plus the new one, and pass that to the setter.
Adding with spread
Spread copies the items of an existing array into a new one. Put the new item before or after the spread to choose where it goes.
import { useState } from 'react';
let nextId = 0;
export default function TodoList() {
const [title, setTitle] = useState('');
const [todos, setTodos] = useState([]);
function handleAdd() {
if (title.trim() === '') return;
setTodos([...todos, { id: nextId++, title, done: false }]);
setTitle('');
}
return (
<>
<input value={title} onChange={(e) => setTitle(e.target.value)} />
<button onClick={handleAdd}>Add</button>
<ul>
{todos.map((t) => (
<li key={t.id}>{t.title}</li>
))}
</ul>
</>
);
}[...todos, newItem] appends. [newItem, ...todos] prepends. Both produce a new array, so React re-renders.
Adding several items in one handler
State is a snapshot. Inside one event handler, todos keeps the same value for the whole call, even after you call the setter. Two calls that both spread todos therefore overwrite each other, and only the last item survives.
function addTwoBroken(title) {
setTodos([...todos, { id: nextId++, title, done: false }]);
// `todos` is still the old array here, so this replaces the first update.
setTodos([...todos, { id: nextId++, title: title + ' (copy)', done: false }]);
}When a new value depends on the previous one, pass an updater function. React queues each updater and gives it the latest queued state.
function addTwo(title) {
setTodos((prev) => [...prev, { id: nextId++, title, done: false }]);
setTodos((prev) => [...prev, { id: nextId++, title: title + ' (copy)', done: false }]);
}Both items are added. Chapter 14 covers updater functions in more detail.
Common errors
| Mistake | Result | Fix |
|---|---|---|
| `todos.push(item); setTodos(todos)` | Same reference, so React may not re-render | `setTodos([...todos, item])` |
| `setTodos(todos.push(item))` | `push` returns the new length, so state becomes a number | Use spread, not `push`, inside the setter |
| `setTodos(todos.concat(item))` | Works. `concat` returns a new array | Fine, but spread is the common style |
| Two setter calls spreading `todos` | The second overwrites the first | Use `setTodos((prev) => ...)` |
Spread only copies the top level of the array. The objects inside are shared with the old array. That is safe here because you are not changing them.
Exercise
A button handler runs setItems([...items, a]); setItems([...items, b]);. After the click, how many of the new items does the list contain, and how do you change the code so both appear?
Show answer
Only b is added, because both calls spread the same old items snapshot and the second replaces the first. Use updaters: setItems((prev) => [...prev, a]); setItems((prev) => [...prev, b]);.
Exercise
Write a one-line update that adds newItem to the start of the items state array without mutating it.
Show answer
setItems([newItem, ...items]);