React useReducer Hook
⏱ Estimated reading time: 2 min
The useReducer hook is an alternative to useState for managing complex state logic. It is especially useful when state updates depend on previous state or involve multiple related values.
Why useReducer?
Use useReducer when:
-
State logic is complex
-
Multiple state values are related
-
Many different actions update the state
-
You want predictable state transitions
It follows a pattern similar to Redux, but is built into React.
Basic Syntax
-
state→ current state -
dispatch→ function to trigger actions -
reducer→ function that updates state -
initialState→ starting state
Reducer Function
A reducer takes the current state and an action, then returns the new state.
Simple Counter Example
Actions
Actions are plain objects:
With payload:
Reducer:
Lazy Initialization
-
Useful for expensive initial state calculations
useReducer vs useState
useReducer | useState |
|---|---|
| Complex logic | Simple state |
| Centralized updates | Direct updates |
| Predictable transitions | Quick and simple |
| Redux-like | Minimal |
Common Use Cases
-
Forms with multiple fields
-
Complex UI state
-
State transitions with rules
-
Managing global state with Context
Combining useReducer with useContext
Best Practices
-
Keep reducers pure
-
Do not mutate state
-
Use clear action types
-
Split large reducers
Key Points
-
useReducermanages complex state -
Reducers define how state changes
-
Actions describe what happened
-
Ideal for predictable state logic
Register Now
Share this Post
← Back to Tutorials