Sub topic 15
The state reducer pattern
This chapter assumes you know function components, props, useState, and the basics of useReducer. You should also have seen a custom hook that returns state and handlers. Here you will learn how a hook can let its callers change how its state updates, without forking the hook.
The problem: fixed behavior inside a reusable hook
A custom hook such as useToggle bundles state and the rules for changing it. Those rules are fixed in the hook's source. Suppose most callers want a plain toggle, but one caller wants a switch that can only be turned on, and another wants to ignore clicks while a save is running.
You have three common options:
- Add a boolean option for each case, such as
onlyTurnOn. The option list grows with every request. - Copy the hook into each project and edit it. Fixes then have to be copied back by hand.
- Let the caller supply the rule for state transitions. This is the state reducer pattern.
The third option keeps the hook small. The hook doesn't need to anticipate every behavior, because callers supply the ones they need.
The idea in one sentence
The hook's state changes go through a reducer. The hook uses a default reducer, and the caller may pass its own reducer to replace or wrap it.
A reducer is a pure function with the shape (state, action) => newState. It does not touch the DOM, call APIs, or mutate its arguments. It only computes the next state from the current state and a description of what happened. useReducer runs that function for you and re-renders when the result changes.
Building it step by step
The hook below uses useReducer. Every change is described as an action object with a type.
import { useReducer } from 'react';
export function toggleReducer(state, action) {
switch (action.type) {
case 'toggle':
return { on: !state.on };
case 'reset':
return { on: action.initialOn };
default:
throw new Error(`Unhandled action type: ${action.type}`);
}
}
export function useToggle({ initialOn = false, reducer = toggleReducer } = {}) {
const [{ on }, dispatch] = useReducer(reducer, { on: initialOn });
const toggle = () => dispatch({ type: 'toggle' });
const reset = () => dispatch({ type: 'reset', initialOn });
function getTogglerProps({ onClick, ...rest } = {}) {
return {
'aria-pressed': on,
onClick: (event) => {
onClick?.(event);
toggle();
},
...rest,
};
}
return { on, toggle, reset, getTogglerProps };
}
// A consumer can override behavior by passing its own reducer:
export const onlyTurnOn = (state, action) =>
action.type === 'toggle' && state.on ? state : toggleReducer(state, action);Three details make the pattern work:
toggleReduceris exported. A caller can import it and call it from inside their own reducer. They only write code for the cases they want to change.- The
reduceroption has a default. Callers who don't care get the standard behavior. - Actions are plain objects with a
type. This is the contract between the hook and its callers. Action types become part of the hook's public API.
Overriding behavior
onlyTurnOn delegates to toggleReducer for every action except one. When the action is toggle and the switch is already on, it returns the current state unchanged. React sees the same state object, so it skips the update.
import { useToggle, onlyTurnOn } from './useToggle';
export function OneWaySwitch() {
const { on, getTogglerProps } = useToggle({ reducer: onlyTurnOn });
return <button {...getTogglerProps()}>{on ? 'On' : 'Off'}</button>;
}The button turns on at the first click. Later clicks do nothing. The hook source did not change.
Why the wrapper delegates
The pattern works well when the caller's reducer handles a few cases and passes the rest to the default. Look at what onlyTurnOn avoids:
- It does not re-implement
reset. - It does not need to know how
toggleflips the value. - If the hook later adds a new action type, the default reducer handles it and the caller's code keeps working.
A caller can also replace the reducer completely. That is allowed, but the caller must then handle every action the hook can dispatch. The default branch above throws on unknown types, so a hand-written reducer that forgets reset will fail loudly when reset() is called.
How the data flows
The diagram shows where the caller's reducer sits in the update path.
Common errors
Mutating state inside the reducer
A reducer must return a new object when something changes. This is wrong:
function badReducer(state, action) {
state.on = !state.on; // mutation
return state;
}React compares the returned value with the previous state. Because it is the same object, React may skip the re-render and the UI will not update. In development, React can also call reducers twice to detect impure code, so mutations show up as odd double toggles.
Doing side effects in the reducer
Calling fetch, console.log for analytics, or localStorage.setItem inside a reducer is a mistake. The reducer may run more than once for a single dispatch. Put side effects in event handlers or in useEffect.
Passing a new reducer on every render
useReducer accepts a changing reducer function and uses the latest one. That is fine for correctness. Still, an inline reducer that closes over props or state can make behavior hard to follow. When the reducer needs outside values, read them deliberately and keep the function a pure computation. Defining it outside the component, as onlyTurnOn is, avoids the problem.
Forgetting the default case
If your reducer does not delegate and has no default, an unknown action returns undefined. The hook then sets state to undefined, and destructuring { on } throws on the next render. Always delegate to the default reducer or throw, as toggleReducer does.
Treating action types as private
Once callers write reducers that switch on 'toggle', renaming that string is a breaking change. Document the action types, or export them as constants:
export const toggleActionTypes = {
toggle: 'toggle',
reset: 'reset',
};The hook and its callers then share one source of truth, and a typo becomes a lookup of an undefined property instead of a silently unhandled action.
Related patterns
State reducer is one of several ways to let callers shape a component's behavior. The table compares it with the patterns that precede it in this tutorial.
| Pattern | Caller changes | Cost to the hook author |
|---|---|---|
| Configuration props | Behavior the author anticipated | A new prop per case |
| Control props | Who owns the state value | Handling controlled and uncontrolled modes |
| Prop getters | Event handlers and attributes on elements | Merging caller props with internal props |
| State reducer | How each state transition is computed | Exposing actions as a public contract |
Control props let the caller own the value itself. The state reducer lets the caller change the rules for computing the next value. The two combine well. The hook can accept a reducer and an on prop together, though the interaction needs care. In controlled mode the reducer's result must be reported through onChange instead of stored.
When to use it, and when not to
Use the state reducer pattern when:
- The hook is shared by several teams or projects with different needs.
- Callers keep asking for small variations on transitions, such as limits, locks, or conditional ignoring.
- State has more than one field, so transitions are worth describing as actions.
Skip it when:
- The state is a single value and only one caller exists.
- Callers only need to be notified of changes. An
onChangecallback is simpler. - You would have to expose many internal actions. Each one becomes an API you must keep stable.
Summary
A state reducer hook routes every state change through a reducer function. The caller can pass a replacement, usually a wrapper that delegates unhandled cases to the exported default. This extends the hook without adding options and without copying its source. The costs are a stable action contract and the need for callers to write pure reducers.
Exercise
A caller wants useToggle to ignore toggle actions while a locked flag is true. The flag lives in the caller's component state. Write a reducer-producing function createLockedReducer(isLocked) that delegates to toggleReducer when not locked, and say what you must be careful about when passing it to the hook.
Show answer
Example: function createLockedReducer(isLocked) { return (state, action) => isLocked && action.type === 'toggle' ? state : toggleReducer(state, action); } Use it as useToggle({ reducer: createLockedReducer(locked) }). Returning the same state object for the ignored action makes React skip the update. Reset still goes through toggleReducer, so it works while locked, which may or may not be wanted. Because a new function is created each render, the reducer must stay pure and only read the isLocked value it was given. Do not call APIs or set state inside it.
Exercise
Why does the default branch of toggleReducer throw an error instead of returning state?
Show answer
Returning state would silently ignore actions the reducer does not recognize, so a typo in an action type or a hand-written reducer that forgets a case would fail without any sign. Throwing makes the mistake visible immediately during development, at the call that caused it.