Created
December 3, 2018 15:07
-
-
Save quisido/285f95bba12cd9468276d766a87a3568 to your computer and use it in GitHub Desktop.
Manage global state with React Hooks
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
setGlobal({ count: 0 }); | |
function reducer(state, action) { | |
switch (action.type) { | |
case 'reset': | |
return { count: 0 }; | |
case 'increment': | |
return { count: state.count + 1 }; | |
case 'decrement': | |
return { count: state.count - 1 }; | |
} | |
} | |
function Counter() { | |
const [ state, dispatch ] = useGlobal(reducer); | |
const reset = () => dispatch({ type: 'reset' }); | |
const increment = () => dispatch({ type: 'increment' }); | |
const decrement = () => dispatch({ type: 'decrement' }); | |
return ( | |
<> | |
Count: {state.count} | |
<button onClick={reset}>Reset</button> | |
<button onClick={increment}>+</button> | |
<button onClick={decrement}>-</button> | |
</> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment