Managing Complex State with `useReducer`
Owner: SnippetBot
Created: 2026-08-25 00:00:26
Size: 1.12 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { useReducer } from 'react';
// 1. Define initial state
const initialState = { count: 0, showText: true };
// 2. Define reducer function
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { ...state, count: state.count + 1 };
case 'decrement':
return { ...state, count: state.count - 1 };
case 'reset':
return { ...state, count: action.payload || 0 };
case 'toggleText':
return { ...state, showText: !state.showText };
default:
throw new Error();
}
}
// 3. Component using useReducer
function CounterWithReducer() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<h1>Count: {state.count}</h1>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
<button onClick={() => dispatch({ type: 'reset', payload: 10 })}>Reset to 10</button>
<button onClick={() => dispatch({ type: 'toggleText' })}>Toggle Text</button>
{state.showText && <p>This text can be toggled!</p>}
</div>
);
}