useReducer is a hook for managing complex state through a reducer function (like Redux). An alternative to useState when update logic becomes complex.
Simple analogy: Imagine an ATM.
How it works:
1// 1. Reducer function (pure logic, no side effects)2function counterReducer(state, action) {3 switch (action.type) {4 case 'increment':5 return { count: state.count + 1 };6 case 'decrement':7 return { count: state.count - 1 };8 case 'reset':9 return { count: 0 };10 default:11 return state;12 }13}1415// 2. Usage in component16function Counter() {17 const [state, dispatch] = useReducer(counterReducer, { count: 0 });1819 return (20 <>21 <p>Count: {state.count}</p>22 <button onClick={() => dispatch({ type: 'increment' })}>+</button>23 <button onClick={() => dispatch({ type: 'decrement' })}>-</button>24 <button onClick={() => dispatch({ type: 'reset' })}>Reset</button>25 </>26 );27}
When useReducer is better than useState:
Advanced pattern — lazy initialization:
1// Expensive initial computation runs only once2const [state, dispatch] = useReducer(reducer, null, () => {3 const saved = localStorage.getItem("form");4 return saved ? JSON.parse(saved) : initialState;5});
Performance note: useReducer is not inherently faster than useState. Its advantage is organizing complex state logic into a predictable, testable reducer function.