How do createContext, Provider and useContext work together?
createContext makes a context object with a default value. A Provider higher in the tree supplies the real value. Any component below it calls useContext(MyContext) to read the nearest provider's value, with no props passed through the middle layers.
Explain it simply
Think of the college Wi-Fi password pinned on the notice board of a floor. Instead of the principal telling each student through ten layers of staff, anyone on that floor just looks at the board. Context is that notice board.
Three steps. First, createContext(defaultValue) makes the board. Second, a Provider wraps part of your tree and sets the real value. Third, any component inside calls useContext(Context) and receives that value.
The default value is used only when there is no Provider above the component. When the provider's value changes, every component reading that context re-renders, no matter how deep it sits.
Example
const ThemeContext = createContext("light");
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
function Button() {
const theme = useContext(ThemeContext); // "dark"
return <button className={theme}>Pay</button>;
}In React 19 you can write <ThemeContext value="dark"> without .Provider.
What to say in the interview
"createContext defines the context, a Provider sets its value for a subtree, and useContext reads the nearest provider's value. It removes prop drilling for things like theme or the logged-in user. All consumers re-render when the value changes, so I keep the value small and stable."
Common mistakes
- Expecting the default value to apply when a Provider exists but passes undefined.