useReducer is a React Hook for managing complex state logic inside a component.
It follows the reducer pattern, similar to Redux — but they are NOT the same.
πΉ What is useReducer?
useReducer is an alternative to useState when:
- State is complex
- Next state depends on previous state
- Multiple related state values exist
π§ͺ Basic Syntax
const [state, dispatch] = useReducer(reducer, initialState);
π§ͺ Example
function reducer(state, action) {
switch (action.type) {
case "INC":
return { count: state.count + 1 };
case "DEC":
return { count: state.count - 1 };
default:
return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<>
<p>{state.count}</p>
<button onClick={() => dispatch({ type: "INC" })}>+</button>
</>
);
}
π§ Why Use useReducer?
β Centralizes state logic
β Predictable state updates
β Cleaner than multiple useState
β Good for complex component logic
π Is useReducer the Same as Redux?
β No — They Are Different
| Feature | useReducer | Redux |
|---|---|---|
| Scope | Component-level | Global app-level |
| Store | No global store | Centralized store |
| Middleware | β No | β Yes |
| DevTools | β No | β Yes |
| Async handling | Manual | Thunk / Saga |
| Boilerplate | Minimal | More |
π§ Key Similarities
β Both use reducer functions
β Both use actions
β Both are predictable
β Same mental model
π― When to Use What?
β
Use useReducer when:
- State is complex but local
- No need for global access
- Component-specific logic
β Use Redux when:
- State is shared across many components
- Need middleware (logging, async)
- Large-scale application
π― Short Interview Answer
useReduceris a React Hook used to manage complex local state using a reducer function.
It follows a similar pattern to Redux but does not replace it, as Redux is meant for global state management with middleware and dev tools.
β One-line summary
useReducer is Redux-like logic for a single component—not a Redux replacement.