⚙️ useReducer() in React
useReducer()
is a powerful hook used for managing complex state logic in React. It's a great alternative to useState()
when dealing with multiple related state values or transitions.
🛠 1. Basic Counter Example
A reducer function takes the current state and an action, then returns a new state.
import { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</div>
);
}
📦 2. When to Use useReducer()
- Managing complex state logic
- Multiple sub-values in a state object
- State transitions based on actions
- More predictable state updates (like Redux)
🧠 3. Anatomy of useReducer
reducer
: function to update statestate
: current state valuedispatch
: function to send actions
🔄 4. Common Pattern
const [state, dispatch] = useReducer(reducer, initialState);
dispatch({ type: 'action_type', payload: value });
You can enhance this pattern with context to build scalable global state management like Redux — without external libraries.