Lab#RE09-1: Prague Itinerary with useReducer

ReactJS labs

reactjs
lab
Lab#RE09
labs
Author

albertprofe

Published

Sunday, November 29, 2026

Modified

Sunday, November 29, 2026

📘 React JS Lab#RE09-1: Prague Itinerary with useReducer

In this lab we take a small to-do app, the Prague itinerary, and keep all its task logic in one reducer.

The app is the final example of react.dev’s Extracting State Logic into a Reducer, with two small changes: the reducer lives in its own file, TaskReducer.js, and Task is split into TaskEditing and TaskView.

Here’s an overview of what we’ll cover:

  1. The data model: an array of tasks {id, text, done} and a nextId counter.
  2. The reducer: one pure function, tasksReducer, with three actions: added, changed and deleted.
  3. useReducer: one line in TaskApp that gives us tasks and dispatch.
  4. Handlers that dispatch: the event handlers no longer set state. They say what happened.
  5. The view: TaskApp renders a title, AddTask and TaskList, and passes data down as props.

By the end of this lab you’ll be able to read a component, find its reducer, and follow one click from the checkbox to the next render.


App.js annotated: 1 data model, 2 reducer, 3 view, 4 handlers, 5 useReducer. On the right, the running app: 6 the <h1>, 7 AddTask, 8 TaskList.

App.js annotated: 1 data model, 2 reducer, 3 view, 4 handlers, 5 useReducer. On the right, the running app: 6 the <h1>, 7 AddTask, 8 TaskList.

The theory behind the hook is on React JS: useReducer. This lab doesn’t repeat it: it applies it to one small app.

1 What you’ll build

The app has three files that matter, plus the reducer:

File What it holds
App.js TaskApp: the data model, useReducer, the handlers and the view
TaskReducer.js tasksReducer: the only place where tasks change
AddTask.js an input and an Add button
TaskList.js TaskList, Task, TaskEditing and TaskView

Who owns which state:

  • TaskApp: tasks, through useReducer
  • AddTask: text, through useState
  • Task: isEditing, through useState

Local state stays local. Only the task list goes through the reducer.

2 From useState to useReducer in three steps

react.dev migrates a component from useState to useReducer in three steps:

  1. Move from setting state to dispatching actions.
  2. Write a reducer function.
  3. Use the reducer from your component.

The sections below follow the annotated screenshot, from 1 to 5.

2.1 Data model (1)

The seed data sits at the bottom of App.js, outside the component. nextId starts at 3 because ids 0, 1 and 2 are taken.

src/App.js
let nextId = 3;

const initialTasks = [
  { id: 0, text: "Visit Kafka Museum", done: true },
  { id: 1, text: "Watch a puppet show", done: false },
  { id: 2, text: "Lennon Wall pic", done: false },
];
  • Each task is a plain object: id, text, done.
  • initialTasks is only the starting value. After the first render, React keeps the current tasks.

2.2 Reducer (2)

The reducer is a pure function: (tasks, action) => nextTasks. It has one case per action type.

src/TaskReducer.js
export default function tasksReducer(tasks, action) {
  switch (action.type) {
    case "added": {
      return [
        ...tasks,
        {
          id: action.id,
          text: action.text,
          done: false,
        },
      ];
    }
    case "changed": {
      return tasks.map((t) => {
        if (t.id === action.task.id) {
          return action.task;
        } else {
          return t;
        }
      });
    }
    case "deleted": {
      return tasks.filter((t) => t.id !== action.id);
    }
    default: {
      throw Error("Unknown action: " + action.type);
    }
  }
}

A reducer runs during rendering, so it must be pure: no requests, no timeouts, no mutations. See Writing reducers well.

  • added: copy the array with spread and append a new task with done: false.
  • changed: map the array and replace the task with the same id.
  • deleted: filter out the task with that id.
  • default: an unknown type is a bug, so it throws.

Every case returns a new array. We never write tasks.push(...) or task.done = true.

react.dev notes that using switch inside reducers is a convention. if/else gives the same result, but a switch is easier to scan at a glance. Each case is wrapped in { } so variables declared in one case don’t clash with another.

2.3 useReducer (5)

One line in TaskApp replaces useState:

src/App.js
import { useReducer } from "react";
import AddTask from "./AddTask.js";
import TaskList from "./TaskList.js";
import tasksReducer from "./TaskReducer.js";

export default function TaskApp() {
  const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);
  // ...
}

useReducer takes two arguments:

  1. a reducer function: tasksReducer
  2. an initial state: initialTasks

And it returns two values:

  1. the current state: tasks
  2. a dispatch function, to send actions to the reducer

2.4 Handlers that dispatch (4)

The handlers no longer compute the next array. Each one builds an action object and calls dispatch.

src/App.js
  function handleAddTask(text) {
    dispatch({
      type: "added",
      id: nextId++,
      text: text,
    });
  }

  function handleChangeTask(task) {
    dispatch({
      type: "changed",
      task: task,
    });
  }

  function handleDeleteTask(taskId) {
    dispatch({
      type: "deleted",
      id: taskId,
    });
  }
  • An action is a plain object. By convention it has a string type that says what happened, plus the minimal data the reducer needs.
  • The handler says what happened. The reducer decides how tasks change.
  • For comparison, with useState the same handler wrote the logic itself: setTasks(tasks.filter((t) => t.id !== taskId)).

2.5 View (3)

The JSX hasn’t changed from the useState version. TaskApp passes tasks down and the handlers down as callbacks.

src/App.js
  return (
    <>
      <h1>Prague itinerary</h1>
      <AddTask onAddTask={handleAddTask} />
      <TaskList
        tasks={tasks}
        onChangeTask={handleChangeTask}
        onDeleteTask={handleDeleteTask}
      />
    </>
  );

In the screenshot, these three elements are 6 (<h1>), 7 (AddTask) and 8 (TaskList).

3 The child components

The children don’t know a reducer exists. They receive props and call callbacks.

3.1 AddTask

AddTask keeps its own text with useState. On Add, it clears the input and calls onAddTask(text).

src/AddTask.js
import { useState } from 'react';

export default function AddTask({onAddTask}) {
  const [text, setText] = useState('');
  return (
    <>
      <input
        placeholder="Add task"
        value={text}
        onChange={(e) => setText(e.target.value)}
      />
      <button
        onClick={() => {
          setText('');
          onAddTask(text);
        }}>
        Add
      </button>
    </>
  );
}

3.2 TaskList, Task, TaskEditing and TaskView

TaskList.js holds four components. Compared with react.dev, the if (isEditing) block is split into two small components.

The four components in TaskList.js

The four components in TaskList.js
src/TaskList.js
import { useState } from "react";

export default function TaskList({ tasks, onChangeTask, onDeleteTask }) {
  return (
    <ul>
      {tasks.map((task) => (
        <li key={task.id}>
          <Task task={task} onChange={onChangeTask} onDelete={onDeleteTask} />
        </li>
      ))}
    </ul>
  );
}

function Task({ task, onChange, onDelete }) {
  const [isEditing, setIsEditing] = useState(false);

  return (
    <label>
      <input
        type="checkbox"
        checked={task.done}
        onChange={(e) => {
          onChange({
            ...task,
            done: e.target.checked,
          });
        }}
      />
      {isEditing ? (
        <TaskEditing
          task={task}
          onChange={onChange}
          onSave={() => setIsEditing(false)}
        />
      ) : (
        <TaskView task={task} onEdit={() => setIsEditing(true)} />
      )}
      <button onClick={() => onDelete(task.id)}>Delete</button>
    </label>
  );
}

function TaskEditing({ task, onChange, onSave }) {
  return (
    <>
      <input
        value={task.text}
        onChange={(e) => {
          onChange({
            ...task,
            text: e.target.value,
          });
        }}
      />
      <button onClick={onSave}>Save</button>
    </>
  );
}

function TaskView({ task, onEdit }) {
  return (
    <>
      {task.text}
      <button onClick={onEdit}>Edit</button>
    </>
  );
}
  • TaskList maps tasks to <li>, with key={task.id}.
  • Task owns isEditing and chooses between editing and viewing.
  • TaskEditing shows an input and Save. Every keystroke calls onChange with a copy of the task.
  • TaskView shows the text and Edit.
  • The checkbox and the text input both call the same onChange, which ends up as one changed action.

4 Data flow

The useReducer loop: dispatch sends an action, useReducer calls reducer() with the state, action.type picks the branch, and the result becomes the new State.

The useReducer loop: dispatch sends an action, useReducer calls reducer() with the state, action.type picks the branch, and the result becomes the new State.

The diagram in the margin is the general loop. Its two branches say Increment and decrement; in this app they are added, changed and deleted.

What happens when you tick Watch a puppet show:

  1. Task: the checkbox onChange calls onChange({ ...task, done: true }).
  2. TaskApp: handleChangeTask(task) runs.
  3. dispatch({ type: "changed", task }).
  4. React calls tasksReducer(tasks, action), which returns a new array.
  5. React re-renders TaskApp, then TaskList, then each Task.

5 useState or useReducer?

react.dev compares both on five points:

  • Code size: useState needs less code up front. useReducer can cut code when many handlers update state in a similar way.
  • Readability: useState is easy while updates are simple. useReducer separates how the state changes from what happened.
  • Debugging: a console.log in the reducer shows every update and the action that caused it.
  • Testing: the reducer is a pure function, so you can export it and test it on its own.
  • Personal preference: both are equivalent, and you can convert back and forth.
Immer

If you prefer to write updates in a mutating style (push, arr[i] = ...), react.dev shows useImmerReducer from the use-immer library. It’s optional, and this lab doesn’t use it.

📘 What to remember

  • All task state lives in TaskApp, behind useReducer(tasksReducer, initialTasks).
  • Handlers dispatch actions: { type: "added" | "changed" | "deleted", ... }.
  • tasksReducer is pure and returns a new array every time.
  • Children get props and callbacks. They never see the reducer.
  • AddTask.text and Task.isEditing are local UI state, so they stay in useState.

6 Exercises (proposals)

Warning

These are proposals for students. They are not in the sandbox.

  1. Log every action: add a console.log(action) at the top of tasksReducer, then add, edit, tick and delete a task. Read the log back.
  2. Clear completed: add a Clear done button and a new action type (for example cleared_done) that removes every task with done: true.
  3. Counter: show “2 of 3 to do” under the title, derived from tasks, without new state.
  4. Ignore empty tasks: don’t add a task when the text is empty. Decide where that check belongs: in AddTask, in the handler or in the reducer.
  5. Test the reducer: tasksReducer is already exported from its own file. Write a test that checks the deleted case.
  6. Go further: share tasks and dispatch through context instead of props, as in Lab#RE08-2.

7 References

Back to top