React useReducer Hook
Manage complex state logic with useReducer hook.
useReducer manages complex state logic better than useState.
Basic Example
```javascript 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> ); } ```
When to Use
- Complex state logic - Multiple sub-values - Next state depends on previous
With Payload
```javascript function reducer(state, action) { switch (action.type) { case 'add': return { count: state.count + action.value }; default: return state; } }
dispatch({ type: 'add', value: 5 }); ```
> Next: Learn useRef hook!