Skip to content

Instantly share code, notes, and snippets.

@quisido
Created December 3, 2018 15:06
Show Gist options
  • Save quisido/f4f3c7754db48cea148638384fd72e1b to your computer and use it in GitHub Desktop.
Save quisido/f4f3c7754db48cea148638384fd72e1b to your computer and use it in GitHub Desktop.
Manage global state with React Hooks
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'reset':
return initialState;
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
}
}
function Counter() {
const [ state, dispatch ] = useReducer(
reducer,
{count: initialCount}
);
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>
</>
);
}
@sahajre
Copy link

sahajre commented May 30, 2019

useReducer hooks second argument should be initialState (which you have already declared) and not {count: initialCount}.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment