Last active
June 20, 2019 17:44
-
-
Save edwintcloud/93297f9de21ead19b9467a42ad5a6185 to your computer and use it in GitHub Desktop.
Context API Component
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, { useState } from 'react'; | |
export const Context = React.createContext(null); | |
export const ContextProvider = ({ initialState, children }) => { | |
const [state, setState] = useState(initialState); | |
const providerActions = { | |
setState: values => | |
setState(prevState => { | |
return { ...prevState, ...values }; | |
}) | |
}; | |
return ( | |
<Context.Provider | |
value={{ | |
state: { ...state }, | |
...providerActions, | |
}} | |
> | |
{children} | |
</Context.Provider> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example App.js wrapped with
ContextProvider
:Example of using
Context
in a component or page: