Created
February 19, 2021 08:38
-
-
Save rockiger/055a0f11d70f6cd69c9c792b8446ba2e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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