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