Step 1: Create a new component to define your Provider and Consumer
In this step we are going to define a custom provider and consumer. We export two things here.
First we export CustomProvider, we will use this to wrap our application at the root of our component stack. Within this component we define our state. Its important we pass both customValue
and setCustomValue
in the value attribute of our provider so we can both access the value AND set the value from within child components.
Secondly, we define the function useCustom
which will provide a clean way to consume our state from child components.
import React, { useContext, useState } from 'react'
const CustomContext = React.createContext();
export function CustomProvider({ children }) {
const [ customValue, setCustomValue ] = useState(false);
return (
<CustomContext.Provider
value={{
customValue, setCustomValue
}}
>
{ children }
</AboutToggleStatusContext.Provider>
)
}
export function useCustom() {
return useContext(AboutToggleStatusContext)
}
Step 2: Wrap the root of your component stack with our new CustomProvider component
...
import { CustomProvider } from './components/CustomContext'
ReactDOM.render(
<CustomProvider>
<App />
</CustomProvider>,
document.getElementById('root')
);
Step 3: Consume our state from any child component of our provider
Now that we are wrapping the base of our application with our CustomProvider
we can access the state we defined in CustomContext
using the function we defined useCustom
.
import { useCustom } from '../components/CustomContext'
export default function App() {
const { customValue, setCustomValue } = useCustom();
return (<>
Custom Value = { customValue ? 'True' : 'False' }
<br/>
<button onClick={() => setCustomValue(!customValue)}>
Toggle Custom Value
</button>
</>)
}
Thats it we're done! We can now access and update the value we defined customValue
from within any child component of our provider and the state will be updated accross the rest of our app.
Top comments (0)