Provider and useContext
- React course
- Beginner
- Lesson 71/84
- 4 min
Learn to provide data with a Provider and read it with useContext.
Provider and useContext
Provider is the component that gives a value to context. It's used as <ThemeContext.Provider value={ '{ "dark" }' }>...</ThemeContext.Provider>; all wrapped components read this value.
On the reading side, the useContext hook comes in: const theme = useContext(ThemeContext);. This call returns the value of the nearest Provider. Without a Provider, the default value is used.
Every time the context changes, all components reading it via useContext re-render. So care is needed to avoid unnecessary changes to the Provider's value prop.
Multiple Providers
You can wrap the same context with different values in different subtrees. If the top level uses <ThemeContext.Provider value="dark"> and a lower level uses <ThemeContext.Provider value="light">, lower-level components read light.
This pattern is handy for showing a different theme inside a modal or adding a language switch. The innermost Provider always wins.
Nested Providers cost a bit but still use the same context. You don't need to define a new context object.
Practice Wrap with Theme.Provider
Complete the skeleton. Write an App component that wraps <h1>Site</h1> with <ThemeContext.Provider value="dark">. Assume ThemeContext is imported. Don't forget to export.
Starter code
// Write the App component hereSample solution
function App() {
return (
<ThemeContext.Provider value="dark">
<h1>Site</h1>
</ThemeContext.Provider>
);
}
export default App;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does useContext return?
- The nearest Provider's value Correct answer
- All Providers
- Always the default
- State
Explanation: useContext returns the nearest Provider's value.
2 Provider prop
Provider passes the value via the ____ prop.
Provider passes the value via the value prop.
Explanation: Provider takes value via the value prop.
3 Match the Provider pattern
| Term | Meaning |
|---|---|
Provider |
Gives value |
value |
Carries data |
useContext |
Reads |
Nested |
Inner wins |