Created
May 17, 2020 00:34
-
-
Save sangkukbae12/bc41169fff85a9575f930e1a361573be to your computer and use it in GitHub Desktop.
How to use React Context effectively
This file contains 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
import React from 'react' | |
const CountStateContext = React.createContext() | |
const CountDispatchContext = React.createContext() | |
function countReducer(state, action) { | |
switch (action.type) { | |
case 'increment': { | |
return {count: state.count + 1} | |
} | |
case 'decrement': { | |
return {count: state.count - 1} | |
} | |
default: { | |
throw new Error(`Unhandled action type: ${action.type}`) | |
} | |
} | |
} | |
function CountProvider({children}) { | |
const [state, dispatch] = React.useReducer(countReducer, {count: 0}) | |
return ( | |
<CountStateContext.Provider value={state}> | |
<CountDispatchContext.Provider value={dispatch}> | |
{children} | |
</CountDispatchContext.Provider> | |
</CountStateContext.Provider> | |
) | |
} | |
function useCountState() { | |
const context = React.useContext(CountStateContext) | |
if (context === undefined) { | |
throw new Error('useCountState must be used within a CountProvider') | |
} | |
return context | |
} | |
function useCountDispatch() { | |
const context = React.useContext(CountDispatchContext) | |
if (context === undefined) { | |
throw new Error('useCountDispatch must be used within a CountProvider') | |
} | |
return context | |
} | |
export {CountProvider, useCountState, useCountDispatch} | |
// The state and dispatch separation is annoying | |
const state = useCountState() | |
const dispatch = useCountDispatch() | |
function useCount() { | |
return [useCountState(), useCountDispatch()] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment