Sub topic 8
Adding to an Array
This chapter assumes you know JavaScript arrays and the spread operator, the basics of useState, and how to handle events in React function components. It covers how to add items to an array held in state, which approaches fail, and the edge cases that cause bugs.
The rule: build a new array
React compares the new state value with the previous one. If you pass the same array reference to the setter, React sees no change. Adding an item to an array in state therefore means creating a new array that contains the old items plus the new one.
The array methods fall into two groups for this purpose.
| Task | Avoid (mutates) | Prefer (returns a new array) |
|---|---|---|
| Add to the end | `push` | `[...arr, item]` or `arr.concat(item)` |
| Add to the start | `unshift` | `[item, ...arr]` |
| Add at a position | `splice` | `slice` plus spread |
push and unshift change the array they are called on and return the new length, not an array. Passing their result to a setter would store a number in your state.
Adding to the end
Spread the existing items into a new array literal and place the new item after them.
import { useState } from 'react';
let nextId = 0;
export default function TodoList() {
const [title, setTitle] = useState('');
const [todos, setTodos] = useState([]);
function addTodo() {
if (title.trim() === '') return;
setTodos([...todos, { id: nextId++, title, done: false }]);
setTitle('');
}
return (
<>
<input value={title} onChange={(e) => setTitle(e.target.value)} />
<button onClick={addTodo}>Add</button>
<ul>
{todos.map((t) => (
<li key={t.id}>{t.title}</li>
))}
</ul>
</>
);
}The array literal [...todos, newItem] is a new array, so React re-renders. The old todos array is untouched, which matters because the current render's event handlers still refer to it.
Adding to the start
Reverse the order inside the literal.
setTodos([{ id: nextId++, title, done: false }, ...todos]);Newest-first lists, such as activity feeds, use this form.
Why `push` fails
This version looks reasonable and does not work:
function addTodo() {
todos.push({ id: nextId++, title, done: false });
setTodos(todos);
}todos.push changes the array in place. setTodos(todos) then hands React the same reference it already holds. React treats the state as unchanged and skips the re-render, so the screen stays stale. The data may even look correct later, when some unrelated state change triggers a render. That intermittent behavior makes mutation bugs hard to trace.
Mutation also breaks things beyond the missed render. In development, React's Strict Mode runs some code twice. A mutating updater function would add the item twice.
Adding several items
Spread more than one source into the same literal.
function addMany(newItems) {
setTodos([...todos, ...newItems]);
}newItems must be an array here. Spreading a non-iterable value such as undefined throws a TypeError.
concat does the same job and also accepts a single value:
setTodos(todos.concat({ id: nextId++, title, done: false }));Use whichever your codebase already prefers. The spread form is more common in React code because it reads the same way for objects.
Adding when the new state depends on the old state
Within one event handler, todos is a snapshot. It holds the value from the render in which the handler was created. Calling the setter twice with [...todos, x] uses the same snapshot both times, so the second call replaces the first.
function addTwoBroken(title) {
setTodos([...todos, { id: nextId++, title, done: false }]);
setTodos([...todos, { id: nextId++, title: title + ' (copy)', done: false }]);
// Only the second item appears.
}Pass an updater function instead. React queues the functions and runs them in order, giving each the result of the previous one.
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. The same technique protects you in asynchronous code, where the snapshot may be out of date by the time a callback runs:
async function addFromServer() {
const item = await fetch('/api/todo').then((r) => r.json());
setTodos((prev) => [...prev, item]);
}If the user added other items while the request was in flight, prev includes them. The snapshot todos would not, and using it would silently discard those items.
Keep updater functions pure. Generate values such as ids outside the updater when you can, because React may call an updater twice in Strict Mode to check for impurity. In the example above, nextId++ inside the updater would burn two ids per call in development. For anything that matters, compute the new item first:
function addTodoSafely(title) {
const item = { id: nextId++, title, done: false };
setTodos((prev) => [...prev, item]);
}The copy is shallow
[...todos, item] copies the array, not the objects inside it. The existing item objects in the new array are the same objects as in the old array. This is fine for adding, because you do not touch them. It matters when you later change an item, which a later chapter covers.
It also affects one common mistake: adding the same object twice.
const template = { id: 0, title: 'New task', done: false };
setTodos([...todos, template, template]);Both entries are one object, so changing one in place changes the other, and both share a duplicate id. Create a fresh object for each entry.
Keys and ids
When you render the list, each item needs a stable key. Assign the id when you create the item, not when you render it. Using the array index as the key causes problems once items can be added at the start or in the middle, because every item's index shifts.
A module-level counter (let nextId = 0) is enough for local examples. It resets on a page reload. For items that must stay unique across sessions, use crypto.randomUUID() or an id from the server.
Limiting or capping the array
Combine adding with slice to keep a bounded list, such as the last five messages.
setMessages((prev) => [...prev, message].slice(-5));slice returns a new array, so this stays non-mutating.
Flow of an add
The diagram shows what happens from the click to the new screen.
The push version ends at the No branch, because the reference it passes is the one React already has.
Common errors
- Calling
pushorunshiftand then passing the same array to the setter. - Passing the return value of
pushto the setter, which stores a number. - Using the same snapshot in two setter calls in one handler instead of an updater function.
- Spreading a value that is not an array.
- Reusing one object for several entries.
- Using the array index as
keyin a list that gains items at the start or middle.
Exercise
A handler runs setItems([...items, 'a']); setItems([...items, 'b']); and the list ends up with only 'b' added. Why does this happen, and how do you fix it so both are added?
Show answer
Both calls read items from the same render snapshot, so each builds a new array from the same old contents. The second call replaces the first result. Use updater functions: setItems((prev) => [...prev, 'a']); setItems((prev) => [...prev, 'b']);. React runs them in order, and each receives the previous result.
Exercise
Write a function that adds a new item to the start of a list held in state, keeping at most 3 items in total.
Show answer
function addNewest(item) { setItems((prev) => [item, ...prev].slice(0, 3)); } The spread builds a new array with the item first, and slice(0, 3) returns a new array limited to the first three entries without mutating anything.