Sub topic 9
Removing from an array with filter
This chapter assumes you know filter and splice in JavaScript, can write a function component with useState, and have read the earlier chapters on treating state as read-only. Here you will remove items from an array in state without mutating it.
Why not splice
splice removes items by changing the array it is called on. If that array is your state, you have mutated it. React then receives the same array reference from your setter and may skip the re-render.
filter never changes the original array. It returns a new array that contains only the items for which your callback returns true. Passing that new array to the setter gives React a new value to render.
The pattern
To remove an item, keep every item whose id differs from the one you want gone:
function removeTodo(id) {
setTodos(todos.filter((t) => t.id !== id));
}The callback reads as "keep this todo if its id is not the one being removed". The original todos array still contains the removed item. The next render receives the new array.
A complete example
This component lets you add todos and delete them. Each todo has a stable id, so the delete button can identify it.
import { useState } from 'react';
let nextId = 3;
export default function TodoList() {
const [todos, setTodos] = useState([
{ id: 0, title: 'Buy milk' },
{ id: 1, title: 'Write report' },
{ id: 2, title: 'Call Ada' },
]);
function removeTodo(id) {
setTodos(todos.filter((t) => t.id !== id));
}
function addTodo() {
setTodos([...todos, { id: nextId++, title: 'New todo' }]);
}
return (
<>
<button onClick={addTodo}>Add</button>
<ul>
{todos.map((todo) => (
<li key={todo.id}>
{todo.title}{' '}
<button onClick={() => removeTodo(todo.id)}>Delete</button>
</li>
))}
</ul>
</>
);
}The arrow function () => removeTodo(todo.id) captures the id of that row. Clicking Delete on "Write report" calls removeTodo(1).
Common errors
- Removing by index.
filtercan pass an index as its second argument, but an index changes whenever the list changes. Use anidunless the list never reorders. - Using
!=or comparing the wrong types. If an id is a number in state but a string from an input ordatasetattribute,!==never matches and nothing is removed. Convert the value first. - Calling
pop,shift, orspliceon state. These mutate the array. Usefilterorsliceinstead. - Expecting
filterto find one item. It keeps or drops every item that matches the test. If ids are not unique, several items disappear at once.
Removing the last items
To drop the first or last item without mutating, use slice:
const withoutFirst = items.slice(1);
const withoutLast = items.slice(0, -1);Both return new arrays and leave items untouched.
Exercise
A list item has the id "7" as a string, because it was read from an input. Your state holds todos with numeric ids. You call setTodos(todos.filter((t) => t.id !== id)) with that string. What happens, and how do you fix it?
Show answer
Nothing is removed. !== compares types, so every numeric id differs from "7" and filter keeps all items. Convert the value first, for example Number(id), so both sides are numbers.