Provider
- React Native course
- Intermediate
- Lesson 15/116
- 5 min
Learn to provide values with Context.Provider.
What is a Provider?
A Provider is the component that supplies a value to a context. Every context object has a .Provider property: <ThemeContext.Provider value={theme}>...</ThemeContext.Provider>. Every component below the Provider can reach this value.
The value prop of a Provider is required; it does not work without it. When the value changes every consuming descendant re-renders. Multiple Providers can nest; the innermost value wins. Wrapping the whole tree once at the app root is a common pattern.
Using a Provider
You use a Provider as a wrapper at the top of the app. For example when you write <ThemeContext.Provider value="dark"><App /></ThemeContext.Provider>, App and all its descendants reach the theme value.
The value usually comes from state: you write const [theme, setTheme] = useState("dark") and pass value={theme}. So when the user changes the theme, all descendants update. Providers can nest too; for example both ThemeContext.Provider and LocaleContext.Provider can wrap the same root.
Practice Wrap with a Provider
Write an App component. Hold theme with useState (initial value "dark"). Wrap <Text>Theme</Text> with <ThemeContext.Provider value={theme}>. Define ThemeContext outside.
Starter code
// Import createContext and useState
// Create ThemeContext with createContext; default null
function App() {
// Hold theme state with useState; initial "dark"
// Wrap <Text>Theme</Text> with Provider; pass theme to value
return <Text>Theme</Text>;
}Sample solution
import { createContext, useState } from "react";
import { Text } from "react-native";
const ThemeContext = createContext(null);
function App() {
const [theme, setTheme] = useState("dark");
return (
<ThemeContext.Provider value={theme}>
<Text>Theme</Text>
</ThemeContext.Provider>
);
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each piece to its role
| Term | Meaning |
|---|---|
Provider |
Provides the value |
value |
Provided data |
useContext |
Reads the value |
createContext |
Creates the context |
2 Use the Provider
<ThemeContext.Provider ____={theme}><App /></ThemeContext.Provider>
<ThemeContext.Provider value={theme}><App /></ThemeContext.Provider>
Explanation: The value prop supplies the value.
3 Which prop of a Provider is required?
<ThemeContext.Provider value={theme}>
<App />
</ThemeContext.Provider>- children
- style
- value Correct answer
- key
Explanation: The value prop is required.