Sub topic 9
Filtering and counting without extra state
This chapter assumes you can write function components, use useState, and read map and filter. It also assumes the to-do app from earlier chapters keeps its list in App. You will add a filter (all, active, completed) and a remaining-items count. Neither needs a new copy of the data.
The problem with duplicate state
A common first attempt stores the filtered list in its own state:
const [todos, setTodos] = useState([]);
const [visibleTodos, setVisibleTodos] = useState([]);Now every change to todos must also update visibleTodos. If you forget once, the screen shows stale data. Two copies of the same information drift apart.
The fix is to store only what cannot be computed. Here that is the list and the selected filter. Everything else is derived data: a value you calculate from state during each render.
Store the filter, derive the rest
Add one piece of state for the current filter. Then compute the visible list and the count in the component body.
const [filter, setFilter] = useState("all");
const visibleTodos = todos.filter((todo) => {
if (filter === "active") return !todo.done;
if (filter === "completed") return todo.done;
return true;
});
const remaining = todos.filter((todo) => !todo.done).length;When todos or filter-renders App. These lines run again and produce fresh values. There is nothing to synchronize.
Render the filtered list and controls
Use visibleTodos in place of todos when you render the list. Keep the keys stable, as in the earlier chapter.
<ul>
{visibleTodos.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
<p>{remaining} {remaining === 1 ? "item" : "items"} left</p>
<div>
{["all", "active", "completed"].map((name) => (
<button
key={name}
type="button"
onClick={() => setFilter(name)}
aria-pressed={filter === name}
>
{name}
</button>
))}
</div>The aria-pressed attribute tells assistive technology which button is selected. Chapter 15 covers accessibility in more detail.
Common errors
- Filtering the state itself. Calling
setTodos(todos.filter(...))to hide items deletes them permanently. A filter should change what you show, not what you store. - Storing the count. A
remainingstate variable goes out of date as soon as you toggle an item. Compute it. - Mutating with
sortorreverse. If you later sort the visible list, use[...visibleTodos].sort(...). These methods change the array in place, and that array may be your state. - Skipping the
key. Items in a filtered list still needkey={todo.id}. Using the index as a key causes wrong checkbox states when the filter changes which items appear.
Check your work
Add three to-dos and check one. The count should read "2 items left". Select "completed" and only the checked item should appear. Select "all" and every item should return. Toggling an item while a filter is active should update the list and count immediately.
Exercise
You want to add a "Clear completed" button. Should it call setVisibleTodos, or should it change todos? Write the one-line handler.
Show answer
It should change todos, because removing completed items is a real change to the data, not a view change. There is no visibleTodos state to set. The handler is setTodos(todos.filter((todo) => !todo.done));. The filtered list and the count then update on the next render.
Exercise
A teammate adds const [remaining, setRemaining] = useState(0) and updates it inside toggleTodo. Name one bug this can cause and the fix.
Show answer
The count can go stale. It is wrong after deleteTodo or any other change that the teammate forgets to mirror. The fix is to delete that state and compute const remaining = todos.filter((todo) => !todo.done).length; during render.