showing results for - "usereduce"
Alexander
03 Apr 2020
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}