December 18, 2018
a method to bypass prop drilling.
to fully share state in your react apps between components and be able to change state from within a child component, refer to this great tutorial.
you can only pass things through a prop called ‘value’, not anything else ( but you can put anything inside )
make, then export your context from your top level component
// at App.js or Index.js
import React from "react";
import YourComponent from "./components/YourComponent"
import YourOtherComponent from "./components/YourOtherComponent"
// create a context (parent state)
export const MainContext = React.createContext();
const appState = {
num: 1,
callbackFunction: callbackFunction(), // you can pass functions too!
anArray: [1, 2, 3],
aString: "some words"
}
const App = props => {
return (
<MainContext.Prodiver value={appState}><YourComponent /> // no need to pass data in
<YourOtherComponent />
</MainContext.Provider>)
}
export const App;
// at YourComponent.js or YourOtherComponent.js
import React from 'react'
import MainContext from '../App.js'
const YourComponent = props => {
return (
<MainContext.Consumer> {/_ now the stuff inside here has your shared data _/}
{v => <p>{v.num}</p>}
</MainContext.Consumer> )
}
export default YourComponent
// at YourComponent.js or YourOtherComponent.js
import React, { useContext } from 'react'
import MainContext from '../App.js'
const YourComponent = props => {
// now EVERYTHING in your component can use the shared data
const sharedState = useContext(MainContext)
return <p>{sharedState.num}</p>
}
export default YourComponent
https://daveceddia.com/usecontext-hook/
https://auth0.com/blog/react-context-api-managing-state-with-ease/