← Back to React, page 3

react-0058 · Easy fresher

Build a todo list with add, toggle, delete and filter using useReducer. Explain your state shape and actions.

Keep one state object with the todos array, a next id and the filter. A pure reducer handles actions such as added, toggled, deleted and filter-changed. The component dispatches actions from handlers and derives the visible list from the state during render. Do not store the filtered list in state.

Full answer

Start with the state. Each todo has an id, text and done flag. Besides the list, the screen needs the current filter ("all", "active" or "done") and a source of new ids. Keeping nextId in state avoids random ids and makes the reducer pure and testable.

Actions describe events: added with text, toggled with an id, deleted with an id, and filtered with a value. The reducer returns a new state for each: spread the old state, and use map and filter for the list so nothing is mutated. Ignore blank text in the added case so the UI cannot create empty items.

The component dispatches in event handlers. The form uses onSubmit and a controlled input for the text. After adding, reset the input. The list uses the todo id as the key.

The visible todos are derived: todos.filter(...) according to the filter, calculated in render. Storing it would duplicate data and invite bugs.

Extras that interviewers may ask. Persist to localStorage in an effect keyed on the todos. Use useReducer's lazy init to read saved data once. Add undo by keeping a history array. Move to a store if the list is needed in many places. Accessibility: a label for the input, real checkboxes and buttons with names that include the todo text.

The reducer here is a plain function, so you can test it without React.

jsx
import { useReducer, useState } from 'react';

const initialState = { nextId: 1, filter: 'all', todos: [] };

function todoReducer(state, action) {
  switch (action.type) {
    case 'added': {
      const text = action.text.trim();
      if (text === '') return state;
      return { ...state, nextId: state.nextId + 1, todos: [...state.todos, { id: state.nextId, text, done: false }] };
    }
    case 'toggled':
      return { ...state, todos: state.todos.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t)) };
    case 'deleted':
      return { ...state, todos: state.todos.filter((t) => t.id !== action.id) };
    case 'filtered':
      return { ...state, filter: action.filter };
    default:
      throw new Error('Unknown action: ' + action.type);
  }
}

export default function TodoApp() {
  const [state, dispatch] = useReducer(todoReducer, initialState);
  const [text, setText] = useState('');

  const visible = state.todos.filter((t) => {
    if (state.filter === 'active') return !t.done;
    if (state.filter === 'done') return t.done;
    return true;
  });

  function handleSubmit(event) {
    event.preventDefault();
    dispatch({ type: 'added', text });
    setText('');
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input type="text" value={text} onChange={(e) => setText(e.target.value)} aria-label="New todo" />
        <button type="submit">Add</button>
      </form>
      <div>
        {['all', 'active', 'done'].map((f) => (
          <button key={f} onClick={() => dispatch({ type: 'filtered', filter: f })} aria-pressed={state.filter === f}>
            {f === 'all' ? 'All' : f === 'active' ? 'Active' : 'Done'}
          </button>
        ))}
      </div>
      <ul>
        {visible.map((t) => (
          <li key={t.id}>
            <input type="checkbox" checked={t.done} onChange={() => dispatch({ type: 'toggled', id: t.id })} aria-label={'Done: ' + t.text} />
            {t.text}
            <button onClick={() => dispatch({ type: 'deleted', id: t.id })}>Delete {t.text}</button>
          </li>
        ))}
      </ul>
      <p>{state.todos.filter((t) => !t.done).length} left</p>
    </div>
  );
}

The check added two todos, ticked the first, switched to the Active filter and deleted the second. Output of the run: after adding two and checking the first: Buy pensDelete Buy pensRead chapter 4Delete Read chapter 4 | 1 left Active filter: Read chapter 4Delete Read chapter 4 | 1 left after deleting the second: | 0 left

Key points

  • State shape: todos, nextId and filter in one object.
  • Actions describe events and the reducer returns new state without mutation.
  • Derive the visible list in render. Do not store it.
  • Use the todo id as the key and real inputs and buttons for accessibility.
  • A pure reducer is easy to test and to persist.

Common mistakes

  • Mutating the todos array in the reducer with push or splice.
  • Storing the filtered list in state.
  • Using the array index as the key for items that can be deleted.
  • Generating ids with Math.random in the reducer, which makes it impure.
  • Forgetting event.preventDefault() on form submit.

Follow-ups

  • How would you persist the list to localStorage and restore it?
  • How would you add undo and redo?
  • How would you write a unit test for the reducer?

Tips

  • Describe the state shape and actions before coding. Interviewers read that as design skill.
  • Keep derived data out of state and say so.
  • Offer persistence and undo as extensions without starting them unprompted.