Skip to content

Instantly share code, notes, and snippets.

@C-E-Rios
Last active October 12, 2020 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save C-E-Rios/a88d199fc524d6664e188eb7e788335d to your computer and use it in GitHub Desktop.
Save C-E-Rios/a88d199fc524d6664e188eb7e788335d to your computer and use it in GitHub Desktop.
Managing state with hooks and context
function countReducer(state, action) {
switch (action.type) {
case "INCREMENT": {
return { count: state.count + 1 };
}
default: {
throw new Error(`Unsupported action type: ${action.type}`);
}
}
}
function CountProvider(props) {
const [state, dispatch] = React.useReducer(countReducer, { count: 0 });
const value = React.useMemo(() => [state, dispatch], [state]);
return <CountContext.Provider value={value} {...props} />;
}
function useCount() {
const context = React.useContext(CountContext);
if (!context) {
throw new Error(`useCount must be used within a CountProvider`);
}
const [state, dispatch] = context;
const increment = () => dispatch({ type: "INCREMENT" });
return {
state,
dispatch,
increment,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment