What does <Context.Provider> do?
What <Context.Provider> does in React
<Context.Provider> is a wrapper component that "provides" a context value to all of its descendants.
It is the only way to set or change the context's value.
Syntax
javascript
<MyContext.Provider value={value}>
{/* descendants that will be able to use this context */}
</MyContext.Provider>In simpler terms:
Provider is like a "radio station",
and all components that use useContext(MyContext) are "receivers".
The Provider "broadcasts" the value, and all subscribers receive it.
Example
javascript
import { createContext, useContext } from "react";
const ThemeContext = createContext("light");
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
return <Button />;
}
function Button() {
const theme = useContext(ThemeContext);
return <button className={theme}>Current theme: {theme}</button>;
}What happens:
- We created the
ThemeContextcontext. - In the
Appcomponent we wrapped the child components in<ThemeContext.Provider>. - We set
value="dark". - The
Buttoncomponent gets"dark"viauseContext(ThemeContext), even though it is deeply nested.
Important details
| Detail | Description |
|---|---|
| Scope | All descendants of the Provider have access to value |
| Updates | If value changes → all subscribers re-render |
| Multiple levels | You can nest several Providers with different values |
| Without a Provider | If a component is not wrapped in a Provider, it gets the defaultValue passed to createContext(defaultValue) |
Example with an updated value
javascript
const ThemeContext = createContext();
function App() {
const [theme, setTheme] = useState("light");
return (
<ThemeContext.Provider value={theme}>
<Toolbar />
<button onClick={() => setTheme(t => t === "light" ? "dark" : "light")}>
Toggle theme
</button>
</ThemeContext.Provider>
);
}Now all components that use useContext(ThemeContext) will automatically change theme when the user clicks the button.
Summary
<Context.Provider>:
- sets the context value (
value), - makes it available to all nested components,
- triggers a re-render of all context consumers when
valuechanges.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.