Skip to content
Tutorials Center
My learning

Topics

Lesson 101 of 132 ยท Projects

Project: Todo App

Build a complete React todo app in four stages - state, a reducer, filtering with derived data, and an accessible editable list with simulated persistence. Every stage runs live.

A todo list is the classic first React project because it contains, in miniature, almost everything real apps do: a list of items, forms, user events, filtering, editing, and rules about how data changes. It is small enough to finish in one sitting and big enough to make you decide where state lives.

We will build it in four stages. Every stage is a complete program you can run and edit, and each one fixes a weakness in the one before. You will practise state, lists and keys, reducers, derived state, refs and accessibility. If any of those feel shaky, skim the linked lessons first.

The plan

Before writing code, decide what the data is and what the screen shows.

  • A todo has an id, a title and a done flag.
  • The app holds a list of todos and the current filter (All, Active, Done).
  • The screen shows a form to add a todo, the visible list, a count of remaining items, and filter and clear buttons.

The component tree we are heading toward:

TEXT
App                      owns the todos (reducer) and the filter
 |- AddTodoForm          owns the text being typed
 |- TodoList
 |   '- TodoItem x N     owns "am I being edited?" and the edit text
 '- Footer               count, filter buttons, clear completed

Notice the rule applied here: state lives in the lowest component that needs it and is lifted only as far as necessary (lifting state up). The text in the add form is only that form's business, so it stays there. The todos are needed by the list and the footer, so App owns them.

One more principle: store the minimum. The number of remaining items and the filtered list can be computed from todos and filter during render, so they are never stored in state.

Stage 1: add and toggle with useState

Start with the smallest thing that works: a list in state, a controlled input, and two operations.

Stage 1: add and toggle

Read the three decisions that matter:

  1. Immutable updates. [...todos, newTodo] and todos.map(...) build new arrays; nothing is mutated, so React sees new references (objects and arrays in state).
  2. Stable ids as keys. Each todo gets a unique id that never changes, so key={todo.id} lets React keep the right checkbox with the right item when the list changes. An array index would break that once you can delete or reorder.
  3. Controlled input. value and onChange keep the text in React state, so clearing it after submit is just setTitle('').

The weakness: every operation is a handler that rewrites the list, and we need two more (delete, rename). The logic is about to scatter, and nextId is awkward state sitting beside todos. Time for a reducer.

Stage 2: move the rules into a reducer

A reducer collects every way the todo list can change in one pure function. The component only reports what happened. We also gain a convenient place for nextId: it is part of the same data, so it lives in the reducer's state.

Because a reducer is a plain function, we can run it with no UI at all. This is the strongest argument for the pattern, so try it first:

Stage 2a: the reducer on its own

Every line of output is a snapshot of the whole list after one action. If a bug appears later, you can reproduce it by replaying actions, with no browser clicking. This is also how you would unit test it.

Now plug the reducer into the component and split the screen into the components from our plan:

Stage 2b: reducer plus components

Compare the handlers to Stage 1: they are now one-liners that say what happened. The count of remaining items is computed in render from state.todos, never stored. AddTodoForm still keeps the typed text in its own useState, because nobody else needs it.

When you have a list in state, always ask: do I store things I could compute? Storing remaining as separate state would create two sources of truth that can disagree. Derive it.

Stage 3: filters and derived data

Filtering is a perfect example of derived state. The filter choice is state; the visible list is computed from todos and filter on each render. We never keep a second, filtered copy of the array, because it would go stale the moment a todo is toggled.

The filter is a UI preference that does not belong in the reducer, so it is a plain useState in App. We also add aria-pressed to the filter buttons so assistive technology knows which one is on.

Stage 3: filtering

Switch to "Done", then uncheck an item: it vanishes from the view immediately, because the view is recomputed. The FILTERS object is a small lookup table: adding a new filter means adding one entry, with no new if branches. Three "empty" messages make the empty state informative rather than blank.

The count remaining uses the active filter's own matches function, so "what counts as active" is defined in exactly one place.

Stage 4: editing, focus, accessibility and persistence

The last stage adds the features that make an app feel finished:

  • Inline editing. A "Rename" button turns the title into an input. Enter saves, Escape cancels, an empty title deletes nothing and simply reverts. Editing state (isEditing, draft) belongs to each TodoItem, so there is no need for the parent to know.
  • Focus management. When the input appears it should receive focus, and when editing ends focus should return to the button that opened it; otherwise keyboard and screen-reader users are dropped at the top of the page. We use a ref and an effect (useRef, useEffect).
  • Live announcements. An element with aria-live="polite" announces the count after each change.
  • Persistence. Real apps save todos to localStorage. The sandbox blocks storage, so we simulate it with a plain in-memory object that has the same getItem/setItem shape. A "Remount app" button throws the whole component tree away and creates it again, which is what a page reload does, and the todos come back from the fake storage.

In a real project you would replace fakeStorage with window.localStorage and change nothing else.

Stage 4: the complete todo app

Add a task, rename another, press "Remount app": the session number goes up, the whole TodoApp is destroyed and rebuilt (that is what changing its key does, see resetting state with a key), and your list is read back from storage. Filter choice is not saved on purpose: it resets to "All", which is usually what people expect after a reload.

What each piece does

  • Lazy initial state. useReducer(todosReducer, undefined, loadState) calls loadState once, on the first render only. Passing loadState() directly would read and parse storage on every render.
  • Saving with an effect. The effect runs after each change to state and writes the JSON. Writing to storage is a side effect, so it does not belong in the reducer or in render (effects).
  • Focus handling. wasEditing remembers whether we just left edit mode, so focus returns to the Rename button only after an edit, not on first mount.
  • Blur saves. onBlur={save} means clicking away commits the edit. Escape sets isEditing to false first, and the unmounting input does not call save again.
  • Accessible names. Buttons say which task they affect (aria-label="Delete Learn JSX"), so a screen reader list of buttons is meaningful.
  • Live region. aria-live="polite" makes the count change audible without moving focus.

The key={session} trick demonstrates persistence without reloading the page. It does not prove that real localStorage works. In your own project, test that by reloading the browser tab.

Ideas to extend it

Try these on your own; each practises something from the course:

  1. Due dates and sorting. Add a due field and sort the visible list by it during render.
  2. Undo. Keep a history array in the reducer state and add an undone action, or look ahead to Tic-Tac-Toe with history for the pattern.
  3. Drag to reorder. See drag and drop.
  4. Server sync. Replace fakeStorage with a simulated API and use optimistic updates.
  5. Tests. Test todosReducer as a plain function and the UI with Testing Library (testing hooks and logic).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should the filtered list be computed during render instead of stored in state?

    Derived data should be calculated from the minimal state (todos and filter). Storing a second copy creates two sources of truth that must be kept in sync.
  2. 2. What is the best key for a todo item?

    Stable ids let React match items across renders when they are added, removed or filtered. Indexes shift, titles can repeat, and random keys force remounting every time.
  3. 3. Why is useReducer(todosReducer, undefined, loadState) better than useReducer(todosReducer, loadState())?

    React calls the init function only on the first render. Calling loadState() as an argument executes it on every render, although only the first result is used.
  4. 4. Where should the text being typed in the Add form live in this app?

    State should live in the lowest component that needs it. Only the form uses the draft text, so it stays local; the todos, needed by several components, live in App.
  5. 5. What does changing the key on <TodoApp key={session} /> do?

    When the key changes, React treats it as a different component: the old one unmounts and a new one mounts, so initial state is computed again (here, from the saved storage).

Summary

  • Plan first: define the data (id, title, done), the screen, and which component owns which state.
  • Stage 1 used useState and immutable updates; stage 2 moved the rules into a pure reducer that can be tested and replayed without a UI.
  • Compute counts and filtered lists during render; store only the minimal state (todos, filter).
  • Use stable ids as keys, accessible names on buttons, aria-pressed for toggle buttons and aria-live for status text.
  • Manage focus when UI changes (edit mode in and out) with refs and effects.
  • Persist by saving state in an effect and loading it lazily with the init function. Use localStorage in a real app.

Next: Project: Tic-Tac-Toe with History