useReducer is useState’s more powerful sibling. When state logic gets complex, useReducer brings predictability.
Basic Usage
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment': return { count: state.count + 1 };
case 'decrement': return { count: state.count - 1 };
case 'reset': return initialState;
default: throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
Count: {state.count}
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
</div>
);
}With Context
Combine useReducer with Context for app-wide state management – a simpler alternative to Redux:
const StateContext = createContext();
const DispatchContext = createContext();
function AppProvider({ children }) {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<StateContext.Provider value={state}>
<DispatchContext.Provider value={dispatch}>
{children}
</DispatchContext.Provider>
</StateContext.Provider>
);
}When to Use useReducer
- Multiple related state updates
- Next state depends on previous state
- Complex state objects
- Want Redux-like patterns without Redux
Discover more from C4: Container, Code, Cloud & Context
Subscribe to get the latest posts sent to your email.