Sub topic 3
Filtering and Counting Without Extra State
Assume you know JavaScript arrays, React function components, props, useState, and basic forms. This chapter keeps the source list as the single source of truth.
Filtering and counting without extra state
Store every to-do in todos. Compute the visible list and remaining count during rendering:
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;This is derived data: a value calculated from existing state. Do not store visibleTodos separately. Duplicate state can become inconsistent.
Editing a to-do inline
Keep an editingId and temporary editText in state. When the user saves, replace only the matching object:
setTodos(todos.map((todo) =>
todo.id === editingId ? { ...todo, title: editText.trim() } : todo
));
setEditingId(null);Render an input when todo.id === editingId; otherwise render the title. Cancel by clearing editingId without changing todos.
Moving update logic into a reducer
A reducer is a pure function that receives current state and an action, then returns the next state. It centralizes list updates:
function todosReducer(todos, action) {
switch (action.type) {
case "toggled":
return todos.map((todo) =>
todo.id === action.id ? { ...todo, done: !todo.done } : todo
);
case "deleted":
return todos.filter((todo) => todo.id !== action.id);
default:
throw new Error(`Unknown action: ${action.type}`);
}
}Use dispatch({ type: "toggled", id }) from event handlers. map, filter, and object spread create new references instead of mutating state.
Saving to localStorage
localStorage stores strings in the browser. useEffect runs after rendering, so it can save changed state:
useEffect(() => {
localStorage.setItem("todos", JSON.stringify(todos));
}, [todos]);Read the initial value with a lazy useState initializer so the storage lookup happens once.
Extracting a custom hook
A custom hook is a function whose name starts with use and which reuses hook logic. A usePersistentState(key, initialValue) hook can combine the lazy read and saving effect. Return [value, setValue], matching useState.
Sharing state with context
Context passes shared values through a component tree without manually forwarding props at every level. Create TodoContext, wrap the app in its provider, and read it with useContext. Use context when many distant components need the same state. Props are usually clearer for local parent-child data.
Making the app accessible
Give every input a visible <label>, use real <button> elements, and provide descriptive names. Keep list keys stable, such as todo.id, rather than array indexes.
Testing with React Testing Library
Test behavior from the user's perspective:
await user.type(screen.getByLabelText(/new task/i), "Buy milk");
await user.click(screen.getByRole("button", { name: /add/i }));
expect(screen.getByText("Buy milk")).toBeTruthy();Exercise
Why should the filtered list usually not be stored in separate state?
Show answer
It is derived from todos and the selected filter, so calculating it avoids duplicated data that can become inconsistent.