What is the useReducer hook and when to prefer it over useState
· Category: React
Short answer
useReducer is a hook for state management with a reducer function and dispatch pattern. It is preferable over useState when state logic is complex or involves multiple sub-values.
How it works
You define a reducer that receives the current state and an action, then returns the new state. Components dispatch actions to trigger updates, making state transitions predictable and testable.
Example
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment': return { count: state.count + 1 };
default: return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return <button onClick={() => dispatch({ type: 'increment' })}>{state.count}</button>;
}
When to use it
- Forms with many fields and validation rules.
- State machines with multiple transitions.
- Scenarios where the next state depends heavily on the previous state.