Skip to content

Instantly share code, notes, and snippets.

@quisido
Created December 3, 2018 15:07
Show Gist options
  • Save quisido/285f95bba12cd9468276d766a87a3568 to your computer and use it in GitHub Desktop.
Save quisido/285f95bba12cd9468276d766a87a3568 to your computer and use it in GitHub Desktop.
Manage global state with React Hooks
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