The Context API
How to pass data deeply through the component tree without having to pass props down manually at every single level.
What is Context?
Context provides a way to 'teleport' data directly to components deep in the tree without passing it via props.
It consists of three parts:
**1. The Context Object:** Created via createContext(). This acts as the key.
**2. The Provider:** <MyContext.Provider value={data}>. This wraps a section of your app and broadcasts the data downwards.
**3. The Consumer:** useContext(MyContext). Any component inside the Provider can use this hook to read the data, no matter how deep it is.
The Prop Drilling Problem
If the top-level App knows the currentUser, but a deeply nested Avatar component 5 levels down needs it, you'd normally have to pass currentUser through Header, Nav, and Profile just to get it there.
This is called 'prop drilling' and it makes intermediate components messy and brittle.
Context solves this by letting Avatar directly read the currentUser broadcasted by App.
The standard pattern
Create the context in a separate file and export it: export const ThemeContext = createContext('light');
In your root component, wrap your app in the provider: <ThemeContext.Provider value='dark'><App /></ThemeContext.Provider>
In any child component, read it: const theme = useContext(ThemeContext);
The Teleportation Effect
Click the toggle to broadcast a new theme from the Provider. Watch how the data 'teleports' directly to the Consumer nodes, ignoring the intermediate components completely.
Click the Provider to broadcast a new theme. Notice how the data 'teleports' directly to the Consumers, completely ignoring the intermediate components.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Context solves the 'prop drilling' problem.
- It requires three parts:
createContext, the<Provider>, anduseContext. - The Provider broadcasts the data downwards.
- The Consumer reads the data, bypassing intermediate components.
- Only use Context for data that changes infrequently.
Done with this concept?
Mark it complete to track your progress. No login needed.