Sikau

React · Day 12 · about 45 min

Project: Todo app

Add, complete, delete and filter tasks.

The classic React app

A todo app uses everything from this unit: a controlled form, state holding an array, immutable updates, lists with keys and derived values.

Designing the state

The todo app is a rite of passage because it touches nearly everything: forms, lists, keys, immutable updates and derived values. When it works, you've proved you can model a small domain in React. Notice how short each handler is — that's the reward for choosing the right state shape before writing any JSX. Most bugs in React apps come from awkward state, not from awkward markup.

Before writing JSX, decide what state the app truly needs. For a todo app that's just two things: the list of tasks (each { id, text, done }) and which filter is selected. The text being typed is a third, local piece for the form. Everything else — how many are left, which tasks are visible — is derived from these during render.

const [tasks, setTasks] = useState([]);
const [filter, setFilter] = useState("all");   // "all" | "active" | "done"
const [text, setText] = useState("");

const visible = tasks.filter((t) =>
  filter === "all" ? true : filter === "done" ? t.done : !t.done,
);
const left = tasks.filter((t) => !t.done).length;

Keeping derived values out of state is what makes the app trustworthy: there's no way for the counter to disagree with the list, because the counter is calculated from the list every time.

The rest of this lesson

  • The handlersexplain
  • State or derived?match
  • Adding a taskorder
  • How many left?predict
  • Build itchallenge
  • Badge quizquiz
  • Unit 2 complete!recap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of React