React Reference ยท State Hooks
React useReducer hook
Reference for React useReducer: manage state with a pure reducer function and dispatched actions, with syntax, edge cases, and when to prefer it over useState.
useReducer is an alternative to useState for state whose updates follow rules. Instead of calling a setter with a new value, you call dispatch with an action (a plain object describing what happened). A reducer function, written once outside the component, takes the current state and the action and returns the next state.
Keeping all transitions in one function makes complex state easier to read, test and debug: every way the state can change is listed in one place.
const [state, dispatch] = useReducer(reducer, initialState); dispatch({ type: 'added', text: 'Buy milk' });
Try it
Syntax
const [state, dispatch] = useReducer(reducer, initialArg, init?);
function useReducer<S, A>( reducer: (state: S, action: A) => S, initialArg: S, init?: (arg: S) => S ): [S, Dispatch<A>];
| Name | Description |
|---|---|
reducer |
A pure function (state, action) => nextState. It must not mutate state. |
initialArg |
The initial state, or the argument passed to init when you provide one. |
init |
Optional initializer that computes the initial state (see useReducer init function). |
Returns: [state, dispatch]. dispatch(action) returns nothing and has a stable identity across renders.
Edge cases: unlike useState, dispatch takes any value as an action; the shape is a convention ({ type, ...payload }). Throwing from the reducer (a common way to reject unknown actions) surfaces during render and reaches error boundaries.
Usage notes
- Reducers are pure. Same state and action in, same result out, with no side effects, no random values, no mutation. StrictMode calls them twice in development to check.
- Return the same state to skip a render. If the reducer returns a value
Object.is-equal to the current state, React bails out of rendering the children. - Dispatch describes, the reducer decides. Name actions after what happened (
'added') rather than what to do ('set_tasks'). - Compared with
useState: a reducer costs more code up front but pays off when many handlers update related fields, when the next state depends on several previous fields, or when you want to unit-test transitions without rendering. - Updates from the same event are batched, and actions run in order against the latest state, so you never need an "updater" form.
- Passing
dispatchdown is cheap because it never changes; combined with context it is a well-known pattern for app-wide state. - Several reducers can live in one component; use one per independent concern.