1const initialState = {count: 0};
2
3function reducer(state, action) {
4 switch (action.type) {
5 case 'increment':
6 return {count: state.count + 1};
7 case 'decrement':
8 return {count: state.count - 1};
9 default:
10 throw new Error();
11 }
12}
13
14function Counter() {
15 const [state, dispatch] = useReducer(reducer, initialState);
16 return (
17 <>
18 Count: {state.count}
19 <button onClick={() => dispatch({type: 'decrement'})}>-</button>
20 <button onClick={() => dispatch({type: 'increment'})}>+</button>
21 </>
22 );
23}