Sub topic 15
The state reducer pattern
This chapter assumes you know useState, have met useReducer, and have read the earlier chapters on custom hooks and prop getters. The state reducer pattern lets a hook's consumer change how its state transitions work, without the hook adding a new prop for every case.
The problem
A reusable hook such as useToggle starts simple. Then consumers ask for variations: "only allow turning on", "ignore clicks after three toggles", "don't reset when disabled". If each request becomes a new option, the hook turns into a pile of flags. The state reducer pattern avoids this by giving the consumer control over the transition logic itself.
How it works
The hook keeps its state in useReducer. It exports its default reducer and accepts an optional reducer option. When the consumer passes one, the hook uses it instead of the default.
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);The custom reducer onlyTurnOn handles one case itself. For every other case it delegates to toggleReducer. Delegation keeps the default behavior and means the consumer only writes the part that differs.
Using it
import { useToggle, onlyTurnOn } from './useToggle';
export function OneWayButton() {
const { on, getTogglerProps } = useToggle({ reducer: onlyTurnOn });
return <button {...getTogglerProps()}>{on ? 'On' : 'Off'}</button>;
}The first click turns the button on. Later clicks dispatch toggle, but onlyTurnOn returns the same state, so nothing changes.
Common errors
- Not delegating. A custom reducer that skips the default one must handle every action type. Otherwise
resethits your owndefaultbranch and throws. - Impure reducers. A reducer must compute the next state from
stateandactiononly. Avoid fetches, timers, and mutation ofstate. - Unknown actions. The default reducer throws on unknown action types. This catches typos early, so keep it.
- Hidden action types. Consumers can only write a reducer if they know the action types. Document them, or export them as constants.
Exercise
Write a reducer named maxThree that wraps toggleReducer and ignores toggle actions once the state has toggled three times. What extra state does it need, and why can't it be written with the current { on } state alone?
Show answer
The reducer needs a counter in state, for example { on, count }, because { on } cannot record how many toggles have happened. The hook's initial state would need a count: 0 field. The reducer then returns state unchanged when action.type === 'toggle' && state.count >= 3. Otherwise it returns { ...toggleReducer(state, action), count: state.count + 1 } for a toggle, and delegates other actions.