useReducer is a React Hook used for state management in functional components.
It is an alternative to useState and works on the reducer pattern, similar to Redux.
const [state, dispatch] = useReducer(reducer, initialState);
It manages state through:
- State
- Actions
- Reducer function
🧠 How useReducer Works
- Component dispatches an action
- Reducer receives current state + action
- Reducer returns new state
- React re-renders with updated state
🧪 Simple Example
Reducer function:
function reducer(state, action) {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
default:
return state;
}
}
Component:
const initialState = { count: 0 };
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
<p>{state.count}</p>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
</>
);
}
✔ Predictable state updates
✔ Centralized logic
🔥 Why Use useReducer Instead of useState?
❌ Problems with useState in Complex State
- Multiple related state variables
- Complex update logic
- Hard to track changes
setUser(prev => ({
...prev,
profile: {
...prev.profile,
name: "Teekam"
}
}));
Messy and error-prone.
✅ Benefits of useReducer
✔ Better for complex state
✔ Clear action-based updates
✔ Easier debugging
✔ Predictable behavior
✔ Cleaner code
✅ When Should You Use useReducer?
✔ State has multiple sub-values
✔ Next state depends on previous state
✔ Complex update logic
✔ Many actions modify same state
✔ Form state management
✔ Toggles, counters, workflows
❌ When NOT to Use useReducer
❌ Simple independent states
❌ Single input values
❌ Minimal logic
Use useState instead.
🆚 useState vs useReducer
| Feature | useState | useReducer |
|---|---|---|
| Simplicity | ✔ Simple | ❌ Verbose |
| Complex state | ❌ Hard | ✔ Easy |
| Central logic | ❌ No | ✔ Yes |
| Debugging | ❌ Hard | ✔ Easy |
🎯 Short Interview Answer
useReduceris a React Hook for managing complex state logic using a reducer function and actions.
It is best used when state updates are complex, involve multiple related values, or depend on previous state.
It provides predictable and centralized state management similar to Redux.
⭐ One-Line Summary
Use useReducer when state logic becomes complex and useState is no longer clean or maintainable.