ReactMedium
Build a todo app
A todo app keeps an array of todo objects ({ id, text, done }) in state, adds items from a form, toggles and deletes them immutably, filters by status, and shows counts derived during render. useReducer keeps the update logic in one place, and persisting to localStorage is a common extension.
Features to implement
- Add a todo (trimmed, non-empty) with a generated ID.
- Toggle done, edit, delete.
- Filter: all, active, completed.
- Remaining count and "clear completed".
- Persist between reloads.
Design decisions to explain
- Reducer for add, toggle, delete and clear actions; pure and testable.
- Stable IDs with
crypto.randomUUID()when creating, used as keys. - Immutable updates (
map,filter, spread). - Derived data: visible todos and counts computed from
todosandfilter. - Lazy initial state reading
localStorageonce; an effect writes changes back. - Form handling: React 19 form action or
onSubmitwithpreventDefault; reset the input after adding. - Accessibility: a labeled input, checkboxes with labels, filter buttons with
aria-pressed.
Extensions
Drag to reorder, due dates, syncing with an API using TanStack Query and optimistic updates (useOptimistic), undo with a history stack.
Code example
tsx
1import { useEffect, useReducer, useState } from "react";23type Todo = { id: string; text: string; done: boolean };4type Action = { type: "added"; text: string } | { type: "toggled"; id: string } | { type: "deleted"; id: string } | { type: "cleared" };5type Filter = "all" | "active" | "done";67function reducer(todos: Todo[], a: Action): Todo[] {8 switch (a.type) {9 case "added": return [...todos, { id: crypto.randomUUID(), text: a.text, done: false }];10 case "toggled": return todos.map((t) => (t.id === a.id ? { ...t, done: !t.done } : t));11 case "deleted": return todos.filter((t) => t.id !== a.id);12 case "cleared": return todos.filter((t) => !t.done);13 }14}1516const load = (): Todo[] => { try { return JSON.parse(localStorage.getItem("todos") ?? "[]"); } catch { return []; } };1718export function TodoApp() {19 const [todos, dispatch] = useReducer(reducer, undefined, load);20 const [filter, setFilter] = useState<Filter>("all");21 useEffect(() => localStorage.setItem("todos", JSON.stringify(todos)), [todos]);2223 const visible = todos.filter((t) => (filter === "all" ? true : filter === "done" ? t.done : !t.done));24 const remaining = todos.filter((t) => !t.done).length;2526 return (27 <section>28 <form action={(fd) => { const text = String(fd.get("text")).trim(); if (text) dispatch({ type: "added", text }); }}>29 <label htmlFor="new">New todo</label> <input id="new" name="text" autoComplete="off" /> <button>Add</button>30 </form>31 <ul>32 {visible.map((t) => (33 <li key={t.id}>34 <label><input type="checkbox" checked={t.done} onChange={() => dispatch({ type: "toggled", id: t.id })} /> {t.text}</label>35 <button aria-label={`Delete ${t.text}`} onClick={() => dispatch({ type: "deleted", id: t.id })}>×</button>36 </li>37 ))}38 </ul>39 <p>{remaining} left</p>40 {(["all", "active", "done"] as Filter[]).map((f) => <button key={f} aria-pressed={filter === f} onClick={() => setFilter(f)}>{f}</button>)}41 <button onClick={() => dispatch({ type: "cleared" })}>Clear completed</button>42 </section>43 );44}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.