0 day streak
javascript / intermediate
Snippet

Managing Complex State with useReducer

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const reducer = (state, action) => {
switch (action.type) {
case 'increment': return { count: state.count + 1 };
case 'decrement': return { count: state.count - 1 };
default: throw new Error();
}
};
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<button onClick={() => dispatch({ type: 'increment' })}>
{state.count}
</button>
);
}
react
Breakdown
1
const [state, dispatch] = useReducer(reducer, initialArg)
Returns the current state paired with a dispatch method.