Sub topic 10
Adding, Removing, and Changing Items in Arrays
This chapter assumes you know useState, event handlers, spread syntax, and the array methods map and filter. It also assumes you know why state must not be mutated: React compares the old and new state values, and a mutated array is the same object as before.
The rule for arrays
Methods that change an array in place, such as push, splice, sort, and reverse, mutate state. Call setTodos with a new array instead. Use spread, map, and filter, which all return new arrays.
| Goal | Avoid (mutates) | Use (returns a new array) |
|---|---|---|
| Add | `push`, `unshift` | `[...todos, item]` |
| Remove | `splice`, `pop` | `filter` |
| Change one item | `todos[i].done = true` | `map` with a copied item |
| Reorder | `sort`, `reverse` | `[...todos].sort(...)` |
A complete todo list
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>
</>
);
}How each operation works
- Add. The spread copies every existing item into a new array, then the new object goes at the end. Put it first to prepend.
- Remove.
filterkeeps every item whose id differs from the one you want gone. - Change.
mapvisits each item. For the matching item it returns a copy with{ ...t, done: !t.done }. For every other item it returns the original object, so unchanged items keep the same reference.
The copy of the matching item matters. Writing t.done = !t.done inside map would mutate the old item, even though map returns a new array.
Keys
Each <li> uses key={t.id}. The id is assigned once and never changes, so React can match each item to its previous render after an add or delete. Do not use the array index as the key when items can be removed or reordered. After a deletion, the remaining items shift to new indexes, and React can attach the wrong state, such as a checkbox or text input, to the wrong row.
Also avoid generating the key during render with Math.random(). A new key on every render makes React discard and recreate every row.
Exercise
Write a function removeDone that deletes every completed todo from the list in the TodoList component, without mutating state.
Show answer
function removeDone() { setTodos(todos.filter(t => !t.done)); } The filter returns a new array that contains only the items where done is false, and setTodos schedules the re-render.