javascript / intermediate
Snippet
Complex State with useReducer
The useReducer hook is used for managing complex state logic in React. It works similarly to Redux, where a reducer function determines the next state based on the current state and a dispatched action.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const initialState = { count: 0 };function reducer(state, action) {switch (action.type) {case 'increment': return { count: state.count + 1 };case 'decrement': return { count: state.count - 1 };default: throw new Error('Unknown action type');}}function Counter() {const [state, dispatch] = React.useReducer(reducer, initialState);return (<>Count: {state.count}<button onClick={() => dispatch({ type: 'decrement' })}>-</button><button onClick={() => dispatch({ type: 'increment' })}>+</button></>);}
react
Breakdown
1
function reducer(state, action)
A pure function that takes the current state and an action, returning a new state object.
2
const [state, dispatch] = useReducer(...)
Returns the current state and a function to send actions to the reducer.