Skip to content

Instantly share code, notes, and snippets.

@rockiger
Created February 19, 2021 08:38
Show Gist options
  • Save rockiger/055a0f11d70f6cd69c9c792b8446ba2e to your computer and use it in GitHub Desktop.
Save rockiger/055a0f11d70f6cd69c9c792b8446ba2e to your computer and use it in GitHub Desktop.
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};
case 'set':
return {count: action.count};
case 'reset':
return initialState;
default:
state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'reset'})}>Reset</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
<button onClick={() => dispatch({type: 'set', count: 25})}>Set to 25</button>
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment