Sub topic 3
Providing a value to a subtree
This chapter assumes you know React function components, JSX, props, and useState. It also assumes you have already called createContext. Here you will supply a value to part of a component tree.
What a Provider does
A context object created with createContext holds nothing by itself. A component reads a value from it only if something above that component supplies one. The supplier is the context's Provider component.
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>The value prop is the data to share. Every component rendered inside the Provider's children can read that value, at any depth, without receiving props. This group of components is the subtree.
A complete example
The example below keeps the theme in state in App and hands it to the subtree.
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext('light');
function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={theme}>
<Toolbar />
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle theme
</button>
</ThemeContext.Provider>
);
}
function Toolbar() {
return <ThemedButton />;
}
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button className={`btn-${theme}`}>Save</button>;
}Toolbar takes no props and passes none. ThemedButton still receives the current theme, because it renders inside the Provider.
How the subtree is defined
The subtree is determined by where components appear in the JSX, not by where they are defined in your files. Consider these points:
- The
Toggle themebutton sits inside the Provider, so it could read the theme too. - A component rendered outside the Provider does not see the value. It gets the default value passed to
createContext, which the next chapter covers. - Components that arrive through
childrencount as inside the Provider. They do not need to be written in the same file.
The value updates when the Provider re-renders
App owns the state. When you click the button, setTheme runs, App re-renders, and the Provider receives a new value. React then updates the components that read this context. You do not write any code to notify them.
React compares the old and new value with Object.is. A string such as 'dark' compares by content. An object or array compares by identity, so a new object on every render counts as a change. Later chapters cover that cost and how to control it.
Common errors
- Forgetting the
valueprop.<ThemeContext.Provider>withoutvaluesuppliesundefined. It does not fall back to the default value. Consumers readundefined. - Putting the consumer outside the Provider. If
ThemedButtonrenders next to<ThemeContext.Provider>instead of inside it, it reads the default value. The app does not crash, which makes the bug easy to miss. - Passing the wrong thing.
value={setTheme}shares the setter but not the theme. Pass what consumers need, or pass an object holding both. - Using the context object as a component. Write
<ThemeContext.Provider>. Do not write<ThemeContext>for the Provider.
Where to place the Provider
Put the Provider as low in the tree as possible while still wrapping every component that needs the value. A narrower subtree limits which components can depend on it. If the whole app needs the value, such as the current user, wrap it near the root.
Exercise
In the following code, what does Sidebar read from ThemeContext, and why? <ThemeContext.Provider value="dark"><Main /></ThemeContext.Provider><Sidebar />
Show answer
Sidebar reads the default value passed to createContext (for example 'light'). It renders outside the Provider, so it is not in the subtree that receives "dark". Only Main and its descendants do.