Skip to main content
03

Todo list

Easyreactstateformslists & keys

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

Build a todo list. The markup is in App.js with one hard-coded item: make the list real.

Requirements

  • The list starts empty, with a short empty-state message such as Nothing to do yet.
  • Typing a task and pressing Enter or clicking Add adds it to the end of the list and clears the input.
  • Leading and trailing spaces are trimmed, and an empty or whitespace-only task is not added.
  • Each item has a checkbox that marks it done or not done. Done items are shown struck through (the done class on the <li> is already styled).
  • Each item has a Delete button that removes it.
  • Below the list, a counter shows how many items are not done: 1 item left, 3 items left.

Accessibility

  • The checkbox and the task text are linked by a <label>, so clicking the text toggles the item.
  • Every Delete button says what it deletes, e.g. Delete Walk the dog, not just Delete.

Note

The preview updates as you type. There are no automated tests for this challenge yet: add, complete and delete a few items, then compare with the reference solution.

Follow-ups interviewers ask

  • Filters: All, Active and Completed, plus a Clear completed button.
  • Edit an item in place on double-click.
  • Persist the list to localStorage so it survives a refresh.
  • What happens with two items that have the same text? Why does that matter for key?

The approach

The state is a list of objects, { id, text, done }, plus the text being typed (draft). The counter is derived on every render: todos.filter((todo) => !todo.done).length. Storing it separately would mean updating it in three places, and sooner or later one of them would forget.

Adding with a form

The input and the Add button sit in a <form> with onSubmit. That gives Enter-to-submit for free, without a keydown handler. event.preventDefault() stops the browser from reloading the page.

The input is controlled (value={draft}), so clearing it after adding is just setDraft('').

Immutable updates

Each operation returns a new array, which is what lets React see the change:

OperationUpdate
Add[...current, newTodo]
Togglecurrent.map(...) returning a new object for the matching id
Deletecurrent.filter(...)

Using the function form, setTodos((current) => ...), means each update works on the latest list even if several happen before a re-render.

Why every item needs an id

key tells React which <li> is which between renders. The index is wrong as soon as an item is deleted from the middle: every item after it shifts, and React reuses the wrong DOM node, including the checkbox's state. The text is wrong too, because two items can have the same text. A generated id is stable and unique. The solution uses a module-level counter; crypto.randomUUID() works as well.

What interviewers look for

  • Derived state for the counter, not a second useState.
  • A <form> with onSubmit, and trimming input.
  • Immutable updates and stable keys, and being able to explain why.
  • Singular and plural in the counter.

Reference solution

src/App.js

jsx
import { useState } from 'react'

let nextId = 1

export default function App() {
  const [todos, setTodos] = useState([])
  const [draft, setDraft] = useState('')

  const remaining = todos.filter((todo) => !todo.done).length

  function addTodo(event) {
    // A form submit handles both the button and Enter.
    event.preventDefault()
    const text = draft.trim()
    if (!text) return
    setTodos((current) => [...current, { id: nextId++, text, done: false }])
    setDraft('')
  }

  function toggleTodo(id) {
    setTodos((current) =>
      current.map((todo) => (todo.id === id ? { ...todo, done: !todo.done } : todo)),
    )
  }

  function deleteTodo(id) {
    setTodos((current) => current.filter((todo) => todo.id !== id))
  }

  return (
    <main className="todo-app">
      <h1>Todo list</h1>
      <form className="todo-form" onSubmit={addTodo}>
        <input
          aria-label="New todo"
          placeholder="What needs to be done?"
          value={draft}
          onChange={(event) => setDraft(event.target.value)}
        />
        <button type="submit">Add</button>
      </form>
      {todos.length === 0 ? (
        <p className="todo-count">Nothing to do yet.</p>
      ) : (
        <>
          <ul className="todo-list">
            {todos.map((todo) => (
              <li key={todo.id} className={todo.done ? 'todo-item done' : 'todo-item'}>
                <label>
                  <input
                    type="checkbox"
                    checked={todo.done}
                    onChange={() => toggleTodo(todo.id)}
                  />
                  <span>{todo.text}</span>
                </label>
                <button
                  type="button"
                  className="delete"
                  aria-label={`Delete ${todo.text}`}
                  onClick={() => deleteTodo(todo.id)}
                >
                  Delete
                </button>
              </li>
            ))}
          </ul>
          <p className="todo-count" aria-live="polite">
            {remaining} {remaining === 1 ? 'item' : 'items'} left
          </p>
        </>
      )}
    </main>
  )
}