useReducer is an alternative to useState for managing complex state logic. It’s usually preferable when you have state that involves multiple sub-values or when the next state depends on the previous one in complex ways.
Signature
Parameters
(prevState: S, action: A) => S
required
A function that takes the current state and an action, and returns the new state. The reducer should be a pure function.
S
required
The initial state value (when using the two-parameter signature).
I
required
The initial argument passed to the
init function (when using the three-parameter signature).(arg: I) => S
A function that receives
initialArg and returns the initial state. Useful for lazy initialization or deriving initial state from props.Returns
Returns a tuple containing:- Current state (
S): The current state value - Dispatch function (
Dispatch<A>): A function to dispatch actions to the reducer
Basic Usage
With Action Payloads
Lazy Initialization
Complex State Management
Passing Dispatch Down
useReducer is usually preferable to useState when:- You have complex state logic involving multiple sub-values
- The next state depends on the previous state in non-trivial ways
- You want to optimize performance for components with deep updates by passing
dispatchdown instead of callbacks
The reducer function should be pure: given the same inputs, it should always return the same output. Don’t perform side effects in reducers.
If you dispatch an action that results in the same state value (compared using
Object.is), Preact will skip re-rendering the component and its children.