Defining the provider

Contexts use the default value that is passed to React.createContext, when there is no provider defined. This is useful for debugging the components when they are not embedded in the app. For example, we could debug a single component as a standalone component. In an app, we usually want to use a provider to provide the value for the context, which we are going to define now.

Edit src/App.js, and in our App function, we simply wrap the Header component with a <ThemeContext.Provider> component, where we pass coral as primaryColor:

const App = () => (
<ThemeContext.Provider value={{ primaryColor: 'coral' }}>
<Header text="Hello World" />
</ThemeContext.Provider>
)

export default App

We can now see that our header color changed from deepskyblue to coral:

Our provider changed the color of the header

If we want to change the value of our context, we can simply adjust the value prop that is passed to the Provider component.

Please note that the default value of a context is not used when we define a provider without passing the value prop to it! If we define a provider without a value prop, then the value of the context will be undefined.

Now that we have defined a single provider for our context, let's move on to defining multiple, nested providers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.185.180