React: A to-do list with a reducer

A to-do list has many kinds of change, which is where a reducer starts to pay off.

What to build

A to-do list whose state is managed by a reducer.

Requirements

  • A form with an input with the id task and an Add button adds a task (ignoring empty text) and empties the input.
  • Each task is an li holding a checkbox that toggles it (the li gets the class done when done), its text in a span, and a Delete button. A button Clear done removes every done task.
  • A p with the id summary shows D of N done.

Constraints

All changes to the list go through one reducer.

Example

Adding "Milk" and "Bread", ticking Milk and pressing Clear done leaves only Bread and "0 of 1 done".

Why it works

Each change is a named action handled in one place, so the list cannot be changed in an unexpected way, and the summary is derived from the list on every render.

Hints

Hint 1

Actions: added (with id and text), toggled (id), deleted (id), cleared.

Hint 2

Create the id in the handler (a counter outside the component) and put it in the action.

Solution

Show one correct solution (try it yourself first)
import { useReducer, useState } from "react";

function tasksReducer(tasks, action) {
  switch (action.type) {
    case "added":
      return [...tasks, { id: action.id, text: action.text, done: false }];
    case "toggled":
      return tasks.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t));
    case "deleted":
      return tasks.filter((t) => t.id !== action.id);
    case "cleared":
      return tasks.filter((t) => !t.done);
    default:
      throw new Error("Unknown action: " + action.type);
  }
}

let nextId = 1;

export default function App() {
  const [tasks, dispatch] = useReducer(tasksReducer, []);
  const [text, setText] = useState("");
  const done = tasks.filter((t) => t.done).length;

  function handleSubmit(event) {
    event.preventDefault();
    if (text.trim() === "") return;
    dispatch({ type: "added", id: nextId++, text: text.trim() });
    setText("");
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input id="task" value={text} onChange={(e) => setText(e.target.value)} />
        <button type="submit">Add</button>
      </form>
      <ul>
        {tasks.map((t) => (
          <li key={t.id} className={t.done ? "done" : undefined}>
            <input type="checkbox" checked={t.done} onChange={() => dispatch({ type: "toggled", id: t.id })} />
            <span>{t.text}</span>
            <button onClick={() => dispatch({ type: "deleted", id: t.id })}>Delete</button>
          </li>
        ))}
      </ul>
      <button onClick={() => dispatch({ type: "cleared" })}>Clear done</button>
      <p id="summary">
        {done} of {tasks.length} done
      </p>
    </div>
  );
}

Lesson: Reducers: organising state changes →