Last active
April 13, 2020 18:25
-
-
Save jonwaldstein/751e7046c7d50d27b6193b4071e2cde5 to your computer and use it in GitHub Desktop.
React context store provider & hook
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
import React, {createContext, useContext, useReducer} from 'react'; | |
import PropTypes from 'prop-types'; | |
// Creates the initial React Context to be consumed by our custom provider and custom hook below | |
const StateContext = createContext(null); | |
const StateContextDispatch = createContext(null); | |
/** | |
* Creates a custom Provider Component where children can update state through a reducer | |
* | |
* | |
*/ | |
const StateProvider = ({reducer, initialState, children}) => { | |
const [state, dispatch] = useReducer(reducer, initialState); | |
return ( | |
<StateContext.Provider value={state}> | |
<StateContextDispatch.Provider value={dispatch}>{children}</StateContextDispatch.Provider> | |
</StateContext.Provider> | |
); | |
}; | |
/** | |
* Custom hook to receive state | |
* | |
*/ | |
const useState = () => useContext(StateContext); | |
const useDispatch = () => useContext(StateContextDispatch); | |
StateProvider.propTypes = { | |
/** Child elements that may use the state */ | |
children: PropTypes.node.isRequired, | |
/** Initial state structure and data */ | |
initialState: PropTypes.shape({}).isRequired, | |
/** Reducer (or combined reducers) set to build the state */ | |
reducer: PropTypes.func.isRequired, | |
}; | |
export {StateProvider, useState, useDispatch}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment