As React applications grow, passing props down through multiple layers of components can become exhausting. This problem is known as Prop Drilling.
To solve this, React provides the Context API, which acts as a global broadcast system, allowing components to share data directly without passing props through intermediate elements.
Advertisement
Nextsem Academy
Lesson: p4-8-context
Slide 1 / 5
P4.8: Context API
As React applications grow, passing props down through multiple layers of components can become exhausting. This problem is known as Prop Drilling.
To solve this, React provides the Context API, which acts as a global broadcast system, allowing components to share data directly without passing props through intermediate elements.
Slide 2 / 5
1. The Prop Drilling Problem
Imagine you have a Theme state declared in App. The App nests a MainLayout, which nests a Sidebar, which nests a ThemeSelectorButton.
To get the theme values to the button, you must pass the props down through every single layout container, even if they don't use it!
Create a new file ThemeContext.js and call createContext().
Example
import { createContext } from 'react';
export const ThemeContext = createContext("dark"); // Default value is "dark"
Interactive Code
Step 2: Provide the Context
Wrap your top-level components inside the Context Provider tag and pass the state value inside the value prop.
Example
import React, { useState } from 'react';
import { ThemeContext } from './ThemeContext';
import MainLayout from './MainLayout';
export default function App() {
const [theme, setTheme] = useState("dark");
return (
<ThemeContext.Provider value={theme}>
<MainLayout />
</ThemeContext.Provider>
);
}
Interactive Code
Step 3: Consume the Context
Inside any child component, use the useContext Hook to read the value directly.
Example
import React, { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
export default function ThemeSelectorButton() {
// Read value directly from global broadcast
const theme = useContext(ThemeContext);
return (
<div className="p-3 bg-slate-900 rounded-xl">
Current Theme is: <span className="font-bold text-blue-400">{theme}</span>
</div>
);
}
Interactive Code
Slide 4 / 5
3. Comparing Local vs Global State Adoption
For local concerns (like toggle states, form inputs), keep using useState. For global concerns (user authentication, active themes, shopping cart items), adopt the Context API.
Curriculum Global State Choices
Preference of developers for context-like global sharing systems vs local states.