Hooks 03 · More complex state
More complex state (useReducer)
When to reach for a reducer instead of useState and how to write it cleanly and type-safely.
Loading lesson…
Hooks 03 · More complex state
When to reach for a reducer instead of useState and how to write it cleanly and type-safely.
Loading lesson…
From lesson React basics 04 you know a task list in state: add, toggle, delete, always as a new array. For every change you have one function that calls setTasks:
function TaskList() {const [tasks, setTasks] = useState<Task[]>([]) // Task = { id, text, done }function handleAdd(id: number, text: string) {setTasks([...tasks, { id, text, done: false }])}function handleToggle(id: number) {setTasks(tasks.map((t) => (t.id === id ? { ...t, done: !t.done } : t)))}function handleDelete(id: number) {setTasks(tasks.filter((t) => t.id !== id))}function handleClearDone() {setTasks(tasks.filter((t) => !t.done))}// …and the JSX that calls these functions}
It works. Now imagine the app grows:
handleAdd – and to the "Duplicate" button, to the import from a file and to everything else that adds tasks. You forget one place and there are eleven tasks.The trouble is that the rules for how the state changes are scattered. Every function works out the new state by itself. useReducer gathers them in one place.
Picture a bank where any employee can open your account and overwrite the balance with a number they worked out themselves. The cashier, the mobile app, the cash machine – each calculates a bit differently. Once the balance doesn't add up, nobody can tell why.
A real bank does it differently. Nobody overwrites the balance. Everyone just records what happened: "deposit $50", "card payment $12". That's called a transaction. The new balance is worked out by one place by fixed rules: add a deposit, subtract a payment, and refuse a payment when the account is empty.
{ type: 'added', text: 'Shopping' }.Not everything needs a bank – you don't keep the change in your pocket by transactions either. The table shows when useState is enough and when a reducer pays off:
| Situation | useState (change in your pocket) | useReducer (a bank account) |
|---|---|---|
| open/closed, the text in a field | ✅ | — |
| a list with 4 or more kinds of changes (add, edit, delete, sort…) | possible, but the rules scatter | ✅ |
| several values that change together (wizard steps, data, errors) | they easily contradict each other | ✅ |
| transition rules ("from step 1 on only with a valid e-mail") | scattered over functions | ✅ |
| you want to test the rules without React | hard | ✅ |
A simple rule: when you start writing a fourth function that calls the same setter, or when several values must change together, it's time for a reducer.
Every reducer is written to the same pattern. We'll show it twice: first in general and then filled in on the task list from the introduction.
import { useReducer } from 'react'// The shape of the state: what the data the reducer looks after looks liketype State = { /* … */ }// ─── 1. WHAT CAN HAPPEN (actions) ────────────────────────// Every event is an object with a type and the data that belongs to it.type Action =| { type: 'something_happened'; data: DataType }| { type: 'other_thing_happened' }// ─── 2. HOW THE STATE CHANGES FROM IT (the reducer) ──────// An ordinary function: (old state, action) → new state. No React.function myReducer(state: State, action: Action): State {switch (action.type) {case 'something_happened':return /* the new state based on the action */case 'other_thing_happened':return /* the new state */}}// ─── 3. WHO REPORTS IT (dispatch) ────────────────────────function MyComponent() {// like useState, only you get dispatch instead of a setterconst [state, dispatch] = useReducer(myReducer, initialState)return <button onClick={() => dispatch({ type: 'other_thing_happened' })}>…</button>}
The template has three parts, and each comes with a question:
dispatch.switch (lesson JavaScript 06) compares action.type with every case and runs the branch that matches. The vertical bar in the Action type means "or" – it's a discriminated union from lesson TypeScript 02: an action is either one object or the other. By the type, TypeScript then knows in every branch what data the action carries.
The answers to the three questions: what can happen is adding, toggling, deleting and clearing the finished ones; the rules are the same ones that were scattered over four functions; the form, the checkboxes and the buttons report it.
// the file src/components/TaskList.tsximport { useReducer, useState } from 'react'// The shape of the state: one task (the whole state is an array of tasks, Task[])interface Task {id: number // the task's number, different for eachtext: string // what needs doingdone: boolean // true = done}// 1. WHAT CAN HAPPEN – four transactionstype Action =| { type: 'added'; id: number; text: string }| { type: 'toggled'; id: number }| { type: 'deleted'; id: number }| { type: 'cleared_done' }// 2. HOW THE STATE CHANGES FROM IT – all the rules in one placefunction tasksReducer(tasks: Task[], action: Action): Task[] {switch (action.type) {case 'added':if (tasks.length >= 10) return tasks // the "at most 10" rule – only here, oncereturn [...tasks, { id: action.id, text: action.text, done: false }]case 'toggled':return tasks.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t))case 'deleted':return tasks.filter((t) => t.id !== action.id)case 'cleared_done':return tasks.filter((t) => !t.done)}}// 3. WHO REPORTS IT – the component just hands in actionsfunction TaskList() {const [tasks, dispatch] = useReducer(tasksReducer, []) // instead of useState: the state and dispatchconst [text, setText] = useState('') // the text in the "New task" field – a small thing, useState is enoughfunction handleAdd() {// the id is made here in the handler and comes in the action (Date.now() doesn't belong in a reducer)dispatch({ type: 'added', id: Date.now(), text }) // "this happened: added"setText('')}return (<><input value={text} onChange={(e) => setText(e.target.value)} /><button onClick={handleAdd}>Add</button><ul>{tasks.map((task) => (<li key={task.id}><inputtype="checkbox"checked={task.done}onChange={() => dispatch({ type: 'toggled', id: task.id })} // "this happened: toggled"/>{task.text}<button onClick={() => dispatch({ type: 'deleted', id: task.id })}>✕</button> {/* "this happened: deleted" */}</li>))}</ul><button onClick={() => dispatch({ type: 'cleared_done' })}>Delete done</button></>)}
The rules didn't change – they just moved from the component into one function. And the "at most 10 tasks" rule is written once: whether the form, the duplicating or the import adds a task, they all hand in the same 'added' action and the reducer judges it the same way.
dispatch({ type: 'toggled', id: 2 }). It calculates nothing itself.tasksReducer(currentTasks, { type: 'toggled', id: 2 }).'toggled' branch and returns a new array in which task 2 has done flipped.What you see: A task list through a reducer. On the right is the action log – the "bank statement". Every dispatch is written into it before the reducer processes it.
Try it:
{"type":"added","text":"Cook lunch"}.cleared_done action removed several tasks at once – only the reducer knows the rule for "what to delete".The takeaway: The component just reports what happened. How the state changes is decided by one place – and the action log is a clear story. Redux DevTools, a tool for the Redux library from lesson Advanced React 09, works exactly like this.
Loading the interactive part…
It's not either–or. One component commonly has a reducer for the "main" data (tasks, a cart, wizard steps) and, next to it, useState for small things unrelated to them – the selected tab or the text of a task being typed. In the demo above, the text of a new task is an ordinary useState.
| useState | useReducer | |
|---|---|---|
| how it changes | setTasks(new array) | dispatch({ type: 'added', … }) |
| where the rule is | in every event handler separately | in the reducer, once |
| what the component gets | the value and a setter | the value and dispatch |
| suits | simple, independent values | data with several kinds of changes and rules |
The table reads by rows; the middle column is useState, the right one a reducer.
A washing machine has programs: ready → washing → spinning → done. It can't be "washing" and "done" at the same time. And while it's washing, the Start button does nothing – there's nowhere to go. A device like that is called a state machine: it has a few clearly named states and rules for moving between them. A reducer is made for it.
You know part of the way from lesson React basics 04 ("One status instead of several yes/no values"): three switches isLoading, isError, isDone give eight combinations but only four make sense, so one status replaces them. Data like the loaded user or the error text would still sit in their own useStates next to it, though – and nothing would stop you from having a user in the 'error' state too. A state machine goes two steps further: every state carries only the data that belongs to it, and the reducer guards how you may move between states.
Loading a user as a state machine:
// User = a made-up user type, say { name: string }type State =| { status: 'idle' } // ready| { status: 'loading' } // washing| { status: 'success'; user: User } // done – and only here is there a user| { status: 'error'; error: string } // broken – and only here is there an error// The actions are what happened – like "Start pressed", "wash finished", "fault" on a washing machinetype Action =| { type: 'load_started' } // loading started (Start pressed)| { type: 'load_succeeded'; user: User } // the data arrived (wash finished)| { type: 'load_failed'; error: string } // something went wrong (fault)function reducer(state: State, action: Action): State {switch (action.type) {case 'load_started':// a transition rule: when it's already loading, another "Start" changes nothingreturn state.status === 'loading' ? state : { status: 'loading' }case 'load_succeeded':return { status: 'success', user: action.user }case 'load_failed':return { status: 'error', error: action.error }}}
And where is the loading itself? Outside the reducer, in an event handler. The reducer gets only the results as actions:
// inside the profile component:const [state, dispatch] = useReducer(reducer, { status: 'idle' })async function load(id: number) {dispatch({ type: 'load_started' }) // washing machine: Start pressed → washingtry {const user = await fetchUser(id) // fetchUser = a made-up function, returns a Promise with a userdispatch({ type: 'load_succeeded', user }) // washing machine: wash finished → done} catch (e) {// e as Error = "trust me, it's an error" (lesson TypeScript 01); .message = the error's textdispatch({ type: 'load_failed', error: (e as Error).message }) // washing machine: fault}}// JSX: a button starts the loading, the content is picked by statusreturn (<><button onClick={() => load(1)} disabled={state.status === 'loading'}>Load</button>{state.status === 'loading' && <p>Loading…</p>}{state.status === 'success' && <p>{state.user.name}</p>} {/* user exists only in the success state */}{state.status === 'error' && <p>{state.error}</p>}</>)
TypeScript then makes sure in the JSX that you can touch state.user only where you've checked state.status === 'success'. A nonsense combination can't even be written.
What you see: The reducer from the example above. The card shows content by the state, below it is the current status. Users are loaded from a fake API with a delay.
Try it:
idle → loading → success and the card shows a name.loading to error. The name from before disappeared – the error state has no user.load_started.idle.The takeaway: The state is always in exactly one of four named states and carries only the data that belongs to it. The reducer guards the transitions.
Loading the interactive part…
A bank works out the balance by rules and does nothing else while doing it – it doesn't call clients or send letters. If it did, every recalculation (during a check, say) would send another letter. A reducer is the same: React may call it more than once, and in development mode it does so on purpose.
// ❌ An impure reducercase 'added':saveToServer(action.text) // a call to the server (a made-up function)return [...tasks, { id: Math.random(), … }] // chance – a different result every time// ✅ A pure reducer: the same state and action always give the same resultcase 'added':return [...tasks, { id: action.id, text: action.text, done: false }]// you create the id in the event handler and send it in the action; you call the server in the handler or an effect
| Rule | Why |
|---|---|
| A reducer is a pure function: no server, timer, Math.random(), Date.now() or mutation | React may call it more than once; the same inputs must give the same result |
| Actions describe what happened: item_added, not set_items | the rule stays in the reducer; set_items would move the calculation back into the component |
| Always return a state – even when the action changes nothing (return the current one) | the same object means "no change" and React re-renders nothing |
| Put an exhaustiveness check with never into default | when you add an action and forget to handle it, TypeScript warns you |
The table reads by rows: the rule on the left, the reason on the right. You know the exhaustiveness check from lesson TypeScript 02 (the section on checking completeness with never): into the default branch you write const exhaustive: never = action. When all actions are handled, nothing ever gets into default. When you forget one, TypeScript reports an error.
This section puts the lesson together into steps to come back to when you write your own reducer. You'll find the same pattern in the Cheat sheets on the React tab.
// the file src/components/ItemList.tsximport { useReducer, useState } from 'react'// ─── THE SHAPE OF THE STATE ──────────────────────────────interface Item { id: number; text: string; done: boolean } // one item of the listtype State = { items: Item[]; filter: 'all' | 'done' } // the whole state: the items and the chosen filter// ─── 1. WHAT CAN HAPPEN (actions) ────────────────────────type Action =| { type: 'item_added'; item: Item }| { type: 'item_removed'; id: number }| { type: 'filter_changed'; filter: State['filter'] } // State['filter'] = the type of the filter property// ─── 2. HOW THE STATE CHANGES FROM IT (the reducer) – outside the componentfunction reducer(state: State, action: Action): State {switch (action.type) {case 'item_added':// a new state object: filter stays, items = the old items + the new one at the endreturn { ...state, items: [...state.items, action.item] }case 'item_removed':// a new state object: items without the item with this idreturn { ...state, items: state.items.filter((i) => i.id !== action.id) }case 'filter_changed':// a new state object: the items stay, only filter changesreturn { ...state, filter: action.filter }default: {// the exhaustiveness check (section 4): only an action no branch handled gets here –// and TypeScript reports it as an error, because nothing can be assigned to the type neverconst exhaustive: never = actionreturn exhaustive}}}// ─── 3. WHO REPORTS IT (the component) ───────────────────export function ItemList() {const [state, dispatch] = useReducer(reducer, { items: [], filter: 'all' }) // the main data → reducerconst [text, setText] = useState('') // a small thing (the field's text) → useState// what can be calculated isn't stored anywhereconst visible = state.filter === 'done' ? state.items.filter((i) => i.done) : state.itemsfunction handleAdd() {// the id is made here in the handler (Date.now() doesn't belong in a reducer) and comes in the actiondispatch({ type: 'item_added', item: { id: Date.now(), text, done: false } })setText('')}return (<><input value={text} onChange={(e) => setText(e.target.value)} /><button onClick={handleAdd}>Add</button>{/* event handlers just report what happened */}<button onClick={() => dispatch({ type: 'filter_changed', filter: 'all' })}>All</button><button onClick={() => dispatch({ type: 'filter_changed', filter: 'done' })}>Done</button><ul>{visible.map((item) => (<li key={item.id}>{item.text}<button onClick={() => dispatch({ type: 'item_removed', id: item.id })}>✕</button></li>))}</ul></>)}// use in a parent: <ItemList />
item_added), not after what to set.Math.random() or Date.now().default holds the exhaustiveness check with never.useState.The reducer is missing a single branch. Fill it in and the switch starts working.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).Loading the interactive part…
The wizard practises sections 1 and 3: all the transition rules (validation – checking what was filled in –, next/back) belong in the reducer, and the component just sends actions. Pixel art adds history: once you have all changes as actions, undo/redo is surprisingly simple. For every reducer, first tell yourself: what can happen, how the state changes from it and who reports it.
Step by step like a washing machine: you don't get from step 1 to step 2 until the reducer confirms the details are fine. What each action should do is in the comments in the code.
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
The classic history pattern (older versions, the current one and newer ones) used by editors and spreadsheets. The selected colour isn't in the history – that's change in your pocket. What exactly should happen is in the comments in the code.
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
useState for the small things.