Sub topic 10
Adding, removing, and changing items in arrays
This chapter assumes you can declare state with useState, write event handlers, use spread syntax, map, and filter, and you know that each render sees a fixed snapshot of state. It shows how to update an array held in state without mutating it.
Why arrays need extra care
React decides whether state changed by comparing the old and new values with Object.is. For an array, that compares references, not contents. If you call todos.push(item) and then setTodos(todos), you pass the same reference. React sees no change and may skip the re-render. Even when the component does re-render for another reason, mutating the old array breaks the snapshot model from earlier chapters, because earlier renders' handlers now see altered data.
The rule is to build a new array and pass that to the setter. Many array methods mutate, so pair each one with a non-mutating alternative.
| Goal | Avoid (mutates) | Prefer (returns a new array) |
|---|---|---|
| Add | `push`, `unshift` | `[...arr, item]`, `[item, ...arr]` |
| Remove | `pop`, `shift`, `splice` | `filter`, `slice` |
| Replace or change | `arr[i] = x`, `item.done = true` | `map` |
| Reorder | `sort`, `reverse` | copy first: `[...arr].sort()` |
A complete example
This list supports all three core operations. Each handler returns a new array, and each item has a stable id that serves as its key.
import { useState } from 'react';
let nextId = 1;
function TodoList() {
const [todos, setTodos] = useState([]);
const [text, setText] = useState('');
function add() {
setTodos([...todos, { id: nextId++, text, done: false }]);
setText('');
}
function toggle(id) {
setTodos(todos.map(t => (t.id === id ? { ...t, done: !t.done } : t)));
}
function remove(id) {
setTodos(todos.filter(t => t.id !== id));
}
return (
<>
<input value={text} onChange={e => setText(e.target.value)} />
<button onClick={add}>Add</button>
<ul>
{todos.map(t => (
<li key={t.id}>
<label>
<input type="checkbox" checked={t.done} onChange={() => toggle(t.id)} />
{t.text}
</label>
<button onClick={() => remove(t.id)}>Delete</button>
</li>
))}
</ul>
</>
);
}Adding items
Spread the old items into a new array literal and put the new item where you want it. At the end, use [...todos, item]. At the start, use [item, ...todos].
To insert in the middle, split with slice. slice copies and never changes the original, unlike splice.
import { useState } from 'react';
function Names() {
const [names, setNames] = useState(['Ana', 'Bo', 'Cy']);
function insertAt(index, name) {
setNames([...names.slice(0, index), name, ...names.slice(index)]);
}
function sortNames() {
setNames([...names].sort());
}
function reverseNames() {
setNames([...names].reverse());
}
return (
<>
<button onClick={() => insertAt(1, 'Zed')}>Insert Zed at 1</button>
<button onClick={sortNames}>Sort</button>
<button onClick={reverseNames}>Reverse</button>
<p>{names.join(', ')}</p>
</>
);
}Sorting and reversing mutate in place, so copy first. The copy is shallow, which is enough because you only reorder references.
Removing items
filter keeps every item for which the callback returns true, so removal means keeping everything except the target. Filter by a stable identifier, not by position, unless the index is the only identity you have. To clear the array, pass [].
Changing items
Use map to produce a new array where one entry is replaced and the rest are reused as they are. For an object item, you must also copy the object that changed. { ...t, done: !t.done } does this. Items you did not touch keep their old references, which is fine because they did not change.
If the item is a primitive, such as a number, return the new value directly:
setScores(scores.map((s, i) => (i === index ? s + 1 : s)));Updating from the previous array
Handlers read the todos snapshot from their own render. If one event queues several updates, each built from the same snapshot, the later ones overwrite the earlier ones. Use an updater function when an update depends on the previous array:
setTodos(prev => [...prev, { id: nextId++, text, done: false }]);Updater functions must be pure. They can run more than once in development (Strict Mode), so do not increment nextId inside them. Compute the id before the call and use it inside.
Keys
A key tells React which rendered item corresponds to which data item across renders. Use the item's id. Avoid key={index} when the list can be reordered, inserted into, or filtered. After a removal, every later item shifts to a new index, so React attaches the wrong component state (such as an input's text or a checkbox) to the wrong item. Generate ids when you create the item, not during render. Do not use Math.random() in key, because a new key on each render forces React to remount every item.
Common pitfalls
- Shallow copies hide nested mutation.
[...todos]copies the array but not the objects inside it. Writingcopy[0].done = truestill mutates the original item. Copy the item too:{ ...item, done: true }. - Using the return value of a mutating method.
setTodos(todos.push(x))sets state to a number, the new length. Likewise,sort()andreverse()return the same mutated array. - Reading state right after setting it.
console.log(todos)aftersetTodos(...)still shows the old array. The new array appears in the next render. - Storing derived arrays. A "completed items" array held in state will drift out of sync with
todos. Compute it during render withtodos.filter(t => t.done). - Deeply nested arrays. Updating an array inside an object inside an array gets verbose. Flatten the state or consider
useReducer.
Exercise
A list of { id, label } items is held in state as items. Write the two handlers: one that renames the item with a given id (rename(id, label)), and one that removes every item whose label is empty. Neither may mutate state.
Show answer
function rename(id, label) { setItems(items.map(i => (i.id === id ? { ...i, label } : i))); } and function removeEmpty() { setItems(items.filter(i => i.label !== '')); }. map returns a new array and copies only the changed object. filter returns a new array without the empty items.
Exercise
A button handler calls todos.push({ id: 9, text: 'x', done: false }); setTodos(todos);. Why might the list not update, and how do you fix it?
Show answer
push mutates the existing array, and setTodos(todos) passes the same reference. React compares references, sees no change, and may skip the re-render. Fix it by creating a new array: setTodos([...todos, { id: 9, text: 'x', done: false }]).