The Context API

How to pass data deeply through the component tree without having to pass props down manually at every single level.

React5 min readConcept 21 of 46

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.

// 1. Create the Context
const ThemeContext = createContext('light');
 
// 2. The Provider (Broadcasts data)
function App() {
const [theme, setTheme] = useState('dark');
return (
<ThemeContext.Provider value={theme}>
</ThemeContext.Provider>
);
}
 
// ... Deeply nested components ...
 
// 3. The Consumer (Reads data directly)
function UserProfile() {
const theme = useContext(ThemeContext);
// Component only re-renders when theme changes
return
;
}
Header
ConsumerSidebar
Nav
ConsumerUserProfile

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.

  1. 1What specific problem does the Context API solve?
  2. 2Which hook do you use to read a context value?
  3. 3When does a component receive the *default value* provided to `createContext()`?

Remember this

  • Context solves the 'prop drilling' problem.
  • It requires three parts: createContext, the <Provider>, and useContext.
  • 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.