Sub topic 9
Removing from an array with filter
This chapter assumes you know JavaScript arrays, the filter method, basic function components, useState, and React event handlers. It covers how to remove items from an array held in state, why filter is the right tool, and the errors that come up in practice.
The goal: a new array without the item
React treats state as a read-only snapshot. To remove an item, you build a new array that leaves the item out, then pass that array to the setter. You don't delete from the array that is already in state.
The tool for this is filter. It never changes the array it is called on. It returns a new array that holds only the elements for which your callback returns a truthy value.
const items = [10, 20, 30, 40];
const result = items.filter((n) => n !== 30);
console.log(result); // [10, 20, 40]
console.log(items); // [10, 20, 30, 40], unchanged
console.log(result === items); // false, a new arrayThe last line matters for React. The setter receives a different reference, so React sees a new value and re-renders.
A removal pattern for a todo list
Here is the removal function from the todo example in this tutorial.
const [todos, setTodos] = useState([]);
function removeTodo(id) {
setTodos(todos.filter((t) => t.id !== id));
}Read the callback as "keep every todo whose id is not the one I want to remove". The condition describes what you keep. Writing it the other way around, as "remove where id matches", is the most common source of bugs here.
Here is a complete component you can run in a React project.
import { useState } from 'react';
const initialTodos = [
{ id: 0, title: 'Buy milk', done: false },
{ id: 1, title: 'Write chapter', done: true },
{ id: 2, title: 'Call Ada', done: false },
];
export default function TodoList() {
const [todos, setTodos] = useState(initialTodos);
function removeTodo(id) {
setTodos(todos.filter((t) => t.id !== id));
}
return (
<ul>
{todos.map((t) => (
<li key={t.id}>
{t.title}{' '}
<button onClick={() => removeTodo(t.id)}>Delete</button>
</li>
))}
</ul>
);
}Each button closes over its own t.id. When you click Delete on "Write chapter", removeTodo(1) runs, and filter returns the other two todos in their original order.
Why not splice or pop
splice, pop, shift, and push change the array in place. If you call them on state, you edit the snapshot React is holding.
function removeTodoWrong(id) {
const index = todos.findIndex((t) => t.id === id);
todos.splice(index, 1); // mutates state
setTodos(todos); // same reference
}Here setTodos(todos) receives the same array reference it already has. React compares the new value with the current one using Object.is. They are identical, so React can skip the re-render. The data underneath may have changed, but the screen does not.
A related trap is findIndex returning -1 when nothing matches. splice(-1, 1) then removes the last item, which is a different bug. filter has no such edge case: if no item matches, it returns a copy with everything still in it.
| Goal | Safe in state | Mutates, avoid on state |
|---|---|---|
| Remove by condition | `filter` | `splice` |
| Remove the last item | `slice(0, -1)` | `pop` |
| Remove the first item | `slice(1)` | `shift` |
| Remove every item | `[]` | `length = 0` |
If you do want splice, copy first: const next = [...todos]; next.splice(index, 1); setTodos(next);. This works, but filter is shorter and has no index to get wrong.
Removing by id, not by index
You can filter by position instead of by id.
function removeAt(index) {
setTodos(todos.filter((_, i) => i !== index));
}The second argument to the callback is the index, and the underscore marks the unused first argument. This is fine for lists that never reorder. For lists that users can sort, insert into, or edit from several places, an index captured at render time can point at a different item by the time the handler runs. Ids stay attached to the item. Prefer ids when your data has them.
Removing several items at once
filter handles multiple removals with no extra code, because the callback runs once per element.
function clearCompleted() {
setTodos(todos.filter((t) => !t.done));
}
function removeMany(idsToRemove) {
const removeSet = new Set(idsToRemove);
setTodos(todos.filter((t) => !removeSet.has(t.id)));
}A Set makes each membership check constant time. With an array and includes, the work grows with the size of both lists. For a few dozen items it doesn't matter, but the Set version costs nothing to write.
Removing when several updates happen together
The todos variable in your handler is the snapshot from the render that created the handler. If you call the setter more than once in one event, each call starts from that same snapshot.
function removeTwoWrong(a, b) {
setTodos(todos.filter((t) => t.id !== a));
setTodos(todos.filter((t) => t.id !== b)); // starts from the old snapshot
}Both calls filter the original array. React applies them in order and the second replaces the first, so only b is removed and a comes back. The fix is an updater function, which receives the latest queued state.
function removeTwo(a, b) {
setTodos((prev) => prev.filter((t) => t.id !== a));
setTodos((prev) => prev.filter((t) => t.id !== b));
}Updater functions also help in asynchronous code. If you delete an item after a network request finishes, todos in your closure may be out of date. setTodos((prev) => prev.filter(...)) reads the current value instead. A single filter that removes both ids is also fine and avoids the problem entirely.
Removing from nested arrays
filter copies only the array it is called on. If the list sits inside an object, you still need to copy the objects on the path to it, as in the nested-object chapter.
const [board, setBoard] = useState({
title: 'Sprint',
tasks: [
{ id: 1, label: 'Design' },
{ id: 2, label: 'Build' },
],
});
function removeTask(id) {
setBoard({
...board,
tasks: board.tasks.filter((t) => t.id !== id),
});
}The spread copies board. The tasks property is then replaced with the filtered array. The tasks you keep are the same object references as before, which is fine because you didn't change them.
Common errors
- Calling
filterand ignoring the result. Writingtodos.filter(...)on its own line does nothing to state, becausefilterreturns a new array and leaves the original alone. You must pass the result to the setter. - Inverting the condition.
t.id === idkeeps only the item you meant to delete. - Using the index from a stale render. Prefer ids, or use the updater form.
- Using
delete todos[i]. This leaves an empty slot in the array (a "hole") and still mutates state. - Generating ids with the array length. After a removal,
todos.lengthcan equal an id that is already in use, which creates duplicate keys. Use a counter or a unique id generator, as thenextIdcounter does in the add example. - Forgetting the
keyprop. Removing an item from the middle of a list without stable keys can make React attach the wrong component state, such as input text, to the wrong row. Usekey={t.id}, not the index.
Does filter copy too much?
filter creates a new array each time, so removing one item from a list of 10,000 allocates a new array of 9,999 references. The objects inside are not copied, only the references. For typical interface lists this cost is small. If you measure a real problem, look at virtualizing the list or restructuring state before you reach for in-place mutation.
Exercise
A component holds const [users, setUsers] = useState([...]). A "Remove inactive" button runs users.filter((u) => u.active); setUsers(users);. The list on screen never changes. What is wrong, and what is the fix?
Show answer
The result of filter is thrown away, and setUsers(users) passes the original array, which has the same reference as the current state, so React sees no change. Pass the filtered array to the setter: setUsers(users.filter((u) => u.active));. If the call might run alongside other updates, use setUsers((prev) => prev.filter((u) => u.active));.
Exercise
You have const [board, setBoard] = useState({ title: 'Sprint', tasks: [...] }). Write removeTask(id) so it removes the task with that id and leaves title unchanged, without mutating state.
Show answer
function removeTask(id) { setBoard({ ...board, tasks: board.tasks.filter((t) => t.id !== id) }); }. The spread copies board with its existing title, and the tasks property is replaced with a new array that omits the matching task.