Skip to content

Instantly share code, notes, and snippets.

@sangkukbae12
Created May 17, 2020 00:34
Show Gist options
  • Save sangkukbae12/bc41169fff85a9575f930e1a361573be to your computer and use it in GitHub Desktop.
Save sangkukbae12/bc41169fff85a9575f930e1a361573be to your computer and use it in GitHub Desktop.
How to use React Context effectively
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