Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 41 ยท Projects and Practice

Project: A Todo List with Redux

Build the classic Redux project in steps: design the state, write the slice, add filters and selectors, test it, then see the Redux Toolkit and React version side by side.

The todo list is the "hello world" of Redux, and it is a good first project because it touches every core idea in a small space: state shape, actions, a reducer, selectors, derived data and tests. We build it in four steps. The logic runs in the editors with a stand-in store; at the end you see the real Redux Toolkit and React code (read-only) so you can copy the structure into a real project.

The requirements

  • Add a todo, toggle it done, delete it, edit its text.
  • Filter the list: all, open, done.
  • Show how many todos are still open.
  • Clear all completed todos at once.

Step 1: design the state

Store the facts only. The filtered list and the open count are derived, so they do not belong in state (state design rules).

JavaScript
{
  todos: {
    ids: [1, 2],                       // order
    entities: { 1: { id: 1, text: 'Buy milk', done: false }, 2: { ... } },
    nextId: 3,                         // simple local id counter
  },
  filter: 'all',                       // 'all' | 'open' | 'done'
}

We use the normalized ids / entities shape so toggling or deleting a todo is a lookup by id and rows can re-render independently.

flowchart LR
  UI["UI events"] -- "dispatch" --> A["actions"]
  A --> R["reducers: todos, filter"]
  R --> S["state"]
  S -- "selectors" --> V["visible todos, open count"]
  V --> UI

The loop you are about to build.

Step 2: reducers and actions

We write plain functions first. The real RTK slice later will be a shorter version of the same thing.

JS Todo reducers and action creators

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice a small design issue the output reveals: blank text was added. Reducers should stay simple; validation of input belongs in the component or in a prepare step (Step 3).

Step 3: selectors, validation and derived data

Selectors produce what the UI shows. We also add a thunk-like function that validates before dispatching.

JS Selectors for visible todos and counts

Press Run (or Ctrl + Enter) to see the console output here.

No output.

If the selectors become expensive (thousands of todos), wrap them with createSelector as in selectors and memoization. For a todo list the plain versions are fine; measure before optimizing.

Step 4: test it

Behaviour-level tests dispatch actions and read through selectors (testing lesson):

JS Tests for the todo logic

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The real version with Redux Toolkit and React (read-only)

JavaScript
// features/todos/todosSlice.js (real Redux Toolkit)
import { createEntityAdapter, createSlice, nanoid, createSelector } from '@reduxjs/toolkit';

const todosAdapter = createEntityAdapter();

const todosSlice = createSlice({
  name: 'todos',
  initialState: todosAdapter.getInitialState({ filter: 'all' }),
  reducers: {
    added: {
      reducer: todosAdapter.addOne,
      prepare: (text) => ({ payload: { id: nanoid(), text: text.trim(), done: false } }),
    },
    toggled(state, action) {
      const todo = state.entities[action.payload];
      if (todo) todo.done = !todo.done;
    },
    removed: todosAdapter.removeOne,
    completedCleared(state) {
      const doneIds = state.ids.filter((id) => state.entities[id].done);
      todosAdapter.removeMany(state, doneIds);
    },
    filterSet(state, action) { state.filter = action.payload; },
  },
});

export const { added, toggled, removed, completedCleared, filterSet } = todosSlice.actions;
export default todosSlice.reducer;

export const { selectAll: selectAllTodos } = todosAdapter.getSelectors((s) => s.todos);
export const selectVisibleTodos = createSelector(
  [selectAllTodos, (s) => s.todos.filter],
  (todos, filter) => todos.filter((t) => filter === 'all' || (filter === 'done') === t.done),
);
JSX
// TodoList.jsx (real React-Redux)
export function TodoList() {
  const todos = useSelector(selectVisibleTodos);
  const dispatch = useDispatch();
  return (
    <ul>
      {todos.map((t) => (
        <li key={t.id}>
          <label>
            <input type="checkbox" checked={t.done} onChange={() => dispatch(toggled(t.id))} />
            {t.text}
          </label>
          <button onClick={() => dispatch(removed(t.id))}>Delete</button>
        </li>
      ))}
    </ul>
  );
}

prepare generates the id outside the reducer, which keeps the reducer pure (no Math.random() or Date.now() inside it).

Extensions to try

  1. Persist the todos with the persistence pattern and a version number.
  2. Add undo/redo with withHistory.
  3. Replace the local list with an RTK Query API and optimistic toggles.
  4. Add due dates (store ISO strings) and a selector for overdue items.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the open count not stored in the state?

    Derived data stored in state can get out of sync.
  2. 2. Why does the real slice use a prepare callback for added?

    Random or time-based values must not be created inside a reducer.
  3. 3. Where does validation of empty input belong?

    Reducers apply facts; input checks happen where input arrives.
  4. 4. Which test best protects against a common reducer bug?

    A no-mutation test catches accidental mutation.

Summary

  • Design state as facts (ids, entities, filter) and derive counts and visible lists.
  • Write reducers and action creators first, then selectors, then the UI.
  • Validate input before dispatch; keep reducers pure (use prepare for ids).
  • Test through dispatch and selectors.
  • The Redux Toolkit version is the same design with less code.

Next: Project: a shopping cart