Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 132 ยท State and Events

useReducer and Reducers

Learn useReducer in React - actions, pure reducer functions, dispatch, the init function, immutable updates, when to choose reducers over useState, and testing reducers as plain functions.

As a component grows, the number of places that change its state grows with it. A todo list might add, rename, toggle, delete and clear items, and each of those lives in a different event handler, each one rewriting the list in its own way. The logic is scattered, and it is easy to make a slightly different mistake in each place.

A reducer gathers all of that logic into one function that sits outside your component. Handlers stop describing how the state changes; they only say what happened by sending an action. The reducer decides the new state. React gives you the useReducer hook to wire such a function into a component. If you know Array.prototype.reduce, the name will feel familiar: it takes the current value and one item and returns the next value. This lesson builds on useState, how state updates work and objects and arrays in state.

The shape of a reducer

A reducer is a plain function with two parameters: the current state and an action. It returns the next state.

JavaScript
function reducer(state, action) {
  // return the next state
}

By convention an action is an object with a type that names what happened, plus any data the reducer needs, often called payload (or just extra fields). Use past-tense or "what the user did" names such as 'added', 'deleted', 'incremented'. They describe an event, not a command to change a variable.

The hook returns the current state and a function named dispatch:

JavaScript
const [state, dispatch] = useReducer(reducer, initialState);
dispatch({ type: 'incremented' });

Calling dispatch does not run the reducer immediately inside your handler. It queues the action; React then calls the reducer with the latest state during the next render, and that return value becomes the state. It follows the same snapshot rule as useState: inside the handler that called dispatch, state still holds the value from the current render.

A counter with a reducer

The component contains no arithmetic at all. Every rule about how count changes is in counterReducer. A switch on action.type is the most common layout, and throwing in default turns a mistyped action name into an immediate error instead of a silent no-op.

Following one dispatch step by step

Press "+10" in the demo above. Here is the exact sequence:

  1. The click handler calls dispatch({ type: 'incremented', amount: 10 }).
  2. React stores the action in the component's queue and schedules a render.
  3. During that render React calls counterReducer({ count: 0 }, action) and gets { count: 10 }.
  4. Your component function runs again with state equal to { count: 10 }.
  5. React updates the DOM text.

If you dispatch three actions in one handler, all three are queued and React feeds them through the reducer in order, each one starting from the result of the previous. That is the same queue behaviour as setCount(c => c + 1) with functional updates, which is why reducers never suffer from stale-state surprises.

A realistic example: a task list

Here is where reducers pay for themselves. The state is an array of tasks, and several actions change it. Study the reducer: every case returns a new array or object and never mutates the old one.

Task list with add, toggle and delete

Notice that the text of the input still uses plain useState. A reducer is for state that changes in several coordinated ways. A throwaway draft string does not need one, and mixing both hooks in one component is perfectly normal.

Also notice where the new id is generated: in the handler, before dispatching, and passed in the action. We will see in a moment why the reducer must not do that itself.

Reducers must be pure

React may call your reducer more than once with the same inputs, and it expects the same output each time. So a reducer follows the rules of pure components:

  • It depends only on its arguments (state and action). No reading Math.random(), Date.now(), or globals.
  • It does no side effects: no fetch, no console.log you rely on, no timers, no DOM, no dispatching.
  • It never mutates state or action. It returns a new object or array when something changed.

The mutation rule is the one that bites. A mutating reducer can look right and still break, because React decides whether to update the screen by comparing the old and new state with Object.is. If you change the old object and return it, the references are equal, so React concludes nothing changed and skips the render.

A mutating reducer that never re-renders (fails on purpose)

Click "Add apple" under each heading. The pure reducer shows Items: 1 at once. The mutating one stays at Items: 0, although its array really did get a new item. Now press "Force a re-render": the mutating list suddenly jumps to the correct count, because the state object was changed behind React's back and only a render triggered by something else revealed it. That is the worst kind of bug: it works "sometimes", depending on what else happens to re-render the component. It also breaks React.memo, effects with dependencies and time-travel features, which all rely on comparing old and new references.

The same reasoning is why React is allowed to call a reducer more than once for the same action. A pure reducer does not care. Generating ids or timestamps inside a reducer is wrong for this reason too: two calls with the same action would produce different results. Create such values before dispatching and put them in the action.

React also helps you find such bugs: in development, <StrictMode> calls every reducer twice for each dispatched action and uses only one result. A pure reducer cannot tell; a mutating one gives itself away.

StrictMode exposes a mutating reducer (fails on purpose)

Click each "Add apple" once. The pure list shows Items: 1. The mutating list shows Items: 2: the second call pushed onto the very same array. Without StrictMode that bug would hide.

Because immutable updates in reducers get verbose with nested data, the Immer library offers useImmerReducer (read-only mention, see objects and arrays in state). Flattening your state, as in choosing a state structure, reduces the pain more than any library.

Initial state and the init function

useReducer(reducer, initialArg, init) accepts an optional third argument. If you pass an init function, React calls init(initialArg) once, on the first render, and uses the return value as the starting state. Use it when building the initial state is a little expensive or needs the argument, and to reuse the same function in a "reset" action.

Lazy initialisation and a reset action

Look in the console panel: init called for Mina appears once when the component first renders, no matter how many times you click. Note the difference: useReducer(reducer, createInitialState(player)) would call the function on every render and throw the result away after the first. Pass the function itself, not its result.

Testing reducers as plain functions

Because a reducer is just (state, action) => state, you can test it without rendering anything: call it, inspect the result. This is a big reason teams like reducers for important logic. Here is a tiny hand-written test harness; real projects use a test runner such as Vitest or Jest (see testing hooks and logic).

Testing a reducer without React

The last two checks matter: they prove the reducer left earlier states untouched, which is the immutability contract. If the reducer mutated, one would already show quantity 2.

useReducer versus useState

They are the same engine underneath. In fact, useState is a simple reducer whose action is "replace with this value". Choose based on how the logic looks:

Question Favours useState Favours useReducer
How many fields? One or two independent values Several that change together
How complex are updates? Replace or toggle Many different transitions, rules, validation
Where should logic live? Short inline handlers are fine You want it in one named place, outside the component
Updates depend on the previous state setX(prev => ...) is enough Each action is a named event
Need to test the logic alone? Rarely Yes, pure function
Debugging Print the new value Log every action and state transition
Code size Less code for simple cases More boilerplate, less per extra case

Do not switch to reducers by default. A single boolean in a useState is clearer than a reducer with two action types. Reach for useReducer when you notice handlers with long chains of setX/setY/setZ, or when several event handlers all modify the same state in related ways. A good test: can you describe each change as an event, such as "task added" or "item removed"? If yes, a reducer fits naturally.

Passing dispatch down

dispatch is stable: it has the same identity on every render. That makes it cheap to pass to children, and it is the reason a reducer pairs so well with context: instead of passing five callbacks down several levels, give descendants a single dispatch. See also lifting state up for how the owner shares it.

Common mistakes

  • Forgetting to return a state in a case. The state becomes undefined. Always return in every branch, and keep the default branch.
  • Mutating inside the reducer (state.count++, array.push, array.sort() on the original). Copy first.
  • Calling dispatch during render. Dispatch from event handlers or effects, never directly in the component body.
  • Doing async work in the reducer. Fetch in the handler or an effect, then dispatch the result: dispatch({ type: 'loaded', data }).
  • Putting Math.random() or Date.now() in the reducer. Create them before dispatching and pass them in the action.
  • Reading state right after dispatch. The handler still sees the old snapshot; the new state arrives on the next render.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a reducer function receive and return?

    A reducer has the signature (state, action) => nextState. React calls it with the latest state and each dispatched action.
  2. 2. Why is Date.now() inside a reducer a bug?

    React may call a reducer more than once for the same action. Impure values such as timestamps or random numbers must be created before dispatching and passed in the action.
  3. 3. A reducer does state.items.push(x) and then returns the same state object. What happens on screen?

    React compares old and new state by reference. A mutated and returned state is the same object, so the render is skipped. A pure reducer returns a new object.
  4. 4. Which call correctly uses the init function of useReducer?

    Pass the initial argument and then the function itself. React calls init(initialArg) once. Calling createInitialState(name) yourself would run it on every render.
  5. 5. When is useReducer usually a better choice than useState?

    Reducers shine when updates are complex and spread over many handlers. For simple, independent values useState is shorter and clearer. Neither hook persists state by itself.

Summary

  • A reducer is a pure function (state, action) => nextState; useReducer returns [state, dispatch].
  • Handlers dispatch actions that describe what happened; the reducer holds all the rules for how state changes.
  • Reducers must not mutate state, perform side effects, or use random/time values; returning the mutated old object makes React skip the update.
  • Pass an init function (not its result) as the third argument for lazy initial state.
  • Reducers are plain functions, so they are easy to test without rendering, and dispatch has a stable identity that is handy for context.
  • Prefer useState for simple state; move to useReducer when the update logic spreads across handlers.

Next: Effects with useEffect