Sub topic 9
Filtering and Counting Without Extra State
This chapter assumes you can read JSX, use useState, and update arrays immutably with map, filter, and spread syntax. It also assumes your App component already holds the todos array, as in the previous chapter on lifting state up.
By the end you will add an All, Active, and Completed filter to the to-do app, and show a count of remaining items. You will do it without storing a second copy of the list.
The problem with storing what you can compute
A common first attempt at filtering keeps two arrays in state: the full list and the visible list.
const [todos, setTodos] = useState([]);
const [visibleTodos, setVisibleTodos] = useState([]);Now every change must update both arrays. Adding, toggling, deleting, and changing the filter each need two set calls that agree with each other. If you forget one, the screen shows stale data. The bug is hard to spot because each array looks correct on its own.
The fix is a rule: store the smallest set of data that can describe the UI, and compute everything else. Data you can calculate from existing state or props is called derived data. Derived data does not belong in state.
For this app the minimal state is:
todos: the array of items.filter: which view the user picked, one of"all","active", or"completed".
The visible list and the remaining count are both functions of those two values.
Deriving the visible list during render
A component function runs again every time its state changes. Any variable you calculate inside the function body is therefore recalculated with fresh values. This is what makes derived data safe.
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;filter here is a state variable, and todos.filter is the array method. They are unrelated, so if that reads confusingly in your codebase, rename the state to view or visibility.
Notice what visibleTodos is not. It is not passed to setTodos, and it never replaces todos. Toggling an item still changes the original array, and the next render recomputes the filtered view from it.
Why no synchronization is needed
Suppose the filter is "active" and the user checks an item. The sequence is:
- The handler calls
setTodoswith a new array in which that item hasdone: true. - React re-renders
App. visibleTodosis computed again from the newtodos. The checked item no longer passes the"active"test, so it disappears.remainingis computed again and drops by one.
You wrote no code that says "remove this item from the active view". The view is a consequence of the data.
Building the filter controls
Add a row of buttons that call setFilter. Marking the current choice with aria-pressed tells assistive technology which button is active, and it gives you something to style.
const FILTERS = ["all", "active", "completed"];
function FilterBar({ filter, onChange }) {
return (
<div role="group" aria-label="Filter to-dos">
{FILTERS.map((name) => (
<button
key={name}
type="button"
aria-pressed={filter === name}
onClick={() => onChange(name)}
>
{name}
</button>
))}
</div>
);
}FilterBar owns no state. It receives the current value and a callback, which is the same props pattern used by TodoItem. The parent keeps ownership of filter.
The button labels are lowercase because they reuse the state values. For polished text, keep a small object that maps each value to a label, or capitalize with CSS.
Putting it together in App
import { useState } from "react";
const FILTERS = ["all", "active", "completed"];
function FilterBar({ filter, onChange }) {
return (
<div role="group" aria-label="Filter to-dos">
{FILTERS.map((name) => (
<button
key={name}
type="button"
aria-pressed={filter === name}
onClick={() => onChange(name)}
>
{name}
</button>
))}
</div>
);
}
function TodoItem({ todo, onToggle, onDelete }) {
return (
<li>
<label>
<input
type="checkbox"
checked={todo.done}
onChange={() => onToggle(todo.id)}
/>
<span style={{ textDecoration: todo.done ? "line-through" : "none" }}>
{todo.title}
</span>
</label>
<button type="button" onClick={() => onDelete(todo.id)}>
Delete
</button>
</li>
);
}
export default function App() {
const [todos, setTodos] = useState([]);
const [text, setText] = useState("");
const [filter, setFilter] = useState("all");
function addTodo(event) {
event.preventDefault();
const title = text.trim();
if (!title) return;
setTodos([...todos, { id: crypto.randomUUID(), title, done: false }]);
setText("");
}
function toggleTodo(id) {
setTodos(todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));
}
function deleteTodo(id) {
setTodos(todos.filter((t) => t.id !== id));
}
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;
return (
<main>
<h1>To-do</h1>
<form onSubmit={addTodo}>
<label>
New task
<input value={text} onChange={(e) => setText(e.target.value)} />
</label>
<button type="submit">Add</button>
</form>
<FilterBar filter={filter} onChange={setFilter} />
<p>{remaining} {remaining === 1 ? "item" : "items"} left</p>
<ul>
{visibleTodos.map((todo) => (
<TodoItem
key={todo.id}
todo={todo}
onToggle={toggleTodo}
onDelete={deleteTodo}
/>
))}
</ul>
</main>
);
}Two details matter here. The list renders visibleTodos, but toggleTodo and deleteTodo operate on todos and match by id. That is why stable ids matter: a filtered list has different positions than the full list, so an index-based update would change the wrong item.
The count uses todos, not visibleTodos. "Items left" means all unfinished items, whatever the current view shows. Choosing the wrong source array is the most common mistake with derived values, so decide for each one which data it describes.
Edge cases
- Empty views. With the filter on
"completed"and nothing finished, the list is empty and the user sees a blank area. Render a message whenvisibleTodos.length === 0, and make it depend on the filter, for example "Nothing completed yet". - Plural wording. The ternary on
remaininghandles "1 item" against "0 items" and "2 items". Zero takes the plural form in English. - Unknown filter values. If
filterheld a value outside the three, thereturn truefallback would show everything. Drawing the buttons fromFILTERSkeeps the set of values in one place. - Storing the filtered array by accident. Calling
setTodos(visibleTodos)would permanently delete the hidden items. Only set state from the full list. - Mutating while filtering.
filterandmapdo not change the original array.sortandreversedo. To sort the visible list, copy first:[...visibleTodos].sort(...), or usetoSortedwhere your target browsers support it.
Do you need useMemo?
You may have heard that filtering on every render is wasteful. For a to-do list it is not. Filtering a few hundred items takes microseconds, far less than rendering their DOM nodes. useMemo caches a computed value between renders and adds a dependency array you must keep correct, so use it only after measuring a real slowdown. A rule of thumb from the React docs is to consider it when a calculation is noticeably slow, for example 1 ms or more when timed with console.time, on realistic data.
When derived data does need state
Derived data is not a ban on state. The filter is real state, because it records a choice the user made and cannot be calculated from todos. The test is: can I compute this from other values I already have? If yes, compute it. If no, store it.
Summary of the pattern
| Value | Source | Stored in state? |
|---|---|---|
| `todos` | User adds, toggles, deletes | Yes |
| `filter` | User clicks a filter button | Yes |
| `visibleTodos` | `todos` and `filter` | No, computed |
| `remaining` | `todos` | No, computed |
Exercise
You want to show a "Clear completed" button that appears only when at least one item is done. Which state should you add, and how do you implement the button's visibility and its click handler?
Show answer
Add no new state. Compute const completedCount = todos.length - remaining; during render and render the button only when completedCount > 0. The click handler calls setTodos(todos.filter((t) => !t.done)), which creates a new array containing only unfinished items. Because the handler works on todos and not on visibleTodos, it clears completed items even when another filter is selected.
Exercise
A teammate stores visibleTodos with useState and updates it inside toggleTodo. The user is on the "active" filter, checks an item, and then switches to "all". The item shows as unchecked. What went wrong, and how do you fix it?
Show answer
The two arrays went out of sync. toggleTodo updated the todos array but the stored visibleTodos copy was changed (or not changed) separately, so the "all" view showed a stale object. The fix is to remove the visibleTodos state and compute it during render from todos and filter, so there is only one source of truth.