Last active
October 12, 2020 10:18
-
-
Save C-E-Rios/a88d199fc524d6664e188eb7e788335d to your computer and use it in GitHub Desktop.
Managing state with hooks and context
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
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