Lab#RE09-1: Prague Itinerary with useReducer
ReactJS labs
📘 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:
- The data model: an array of tasks
{id, text, done}and anextIdcounter. - The reducer: one pure function,
tasksReducer, with three actions:added,changedanddeleted. useReducer: one line inTaskAppthat gives ustasksanddispatch.- Handlers that dispatch: the event handlers no longer set state. They say what happened.
- The view:
TaskApprenders a title,AddTaskandTaskList, 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.
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 running app: gk5nhk.csb.app (CodeSandbox
todo-tasks-reducer). CodeSandbox shows a warning page first; click Yes, proceed to preview. - The component tree: Prague itinerary: component tree. Four components, one reducer.
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, throughuseReducerAddTask:text, throughuseStateTask:isEditing, throughuseState
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:
- Move from setting state to dispatching actions.
- Write a reducer function.
- 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
- Each task is a plain object:
id,text,done. initialTasksis only the starting value. After the first render, React keeps the currenttasks.
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 withdone: false.changed:mapthe array and replace the task with the sameid.deleted:filterout the task with thatid.default: an unknowntypeis a bug, so it throws.
Every case returns a new array. We never write tasks.push(...) or task.done = true.
switch?
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
useReducer takes two arguments:
- a reducer function:
tasksReducer - an initial state:
initialTasks
And it returns two values:
- the current state:
tasks - a
dispatchfunction, 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
- An action is a plain object. By convention it has a string
typethat says what happened, plus the minimal data the reducer needs. - The handler says what happened. The reducer decides how
taskschange. - For comparison, with
useStatethe 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
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.
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>
</>
);
}TaskListmapstasksto<li>, withkey={task.id}.TaskownsisEditingand chooses between editing and viewing.TaskEditingshows an input and Save. Every keystroke callsonChangewith a copy of the task.TaskViewshows the text and Edit.- The checkbox and the text input both call the same
onChange, which ends up as onechangedaction.
4 Data flow
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:
Task: the checkboxonChangecallsonChange({ ...task, done: true }).TaskApp:handleChangeTask(task)runs.dispatch({ type: "changed", task }).- React calls
tasksReducer(tasks, action), which returns a new array. - React re-renders
TaskApp, thenTaskList, then eachTask.
5 useState or useReducer?
react.dev compares both on five points:
- Code size:
useStateneeds less code up front.useReducercan cut code when many handlers update state in a similar way. - Readability:
useStateis easy while updates are simple.useReducerseparates how the state changes from what happened. - Debugging: a
console.login 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.
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, behinduseReducer(tasksReducer, initialTasks). - Handlers dispatch actions:
{ type: "added" | "changed" | "deleted", ... }. tasksReduceris pure and returns a new array every time.- Children get props and callbacks. They never see the reducer.
AddTask.textandTask.isEditingare local UI state, so they stay inuseState.
6 Exercises (proposals)
These are proposals for students. They are not in the sandbox.
- Log every action: add a
console.log(action)at the top oftasksReducer, then add, edit, tick and delete a task. Read the log back. - Clear completed: add a Clear done button and a new action type (for example
cleared_done) that removes every task withdone: true. - Counter: show “2 of 3 to do” under the title, derived from
tasks, without new state. - 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. - Test the reducer:
tasksReduceris already exported from its own file. Write a test that checks thedeletedcase. - Go further: share
tasksanddispatchthrough context instead of props, as in Lab#RE08-2.


