Component Patterns and Context APILesson 4.1
React Context API: solving prop drilling
createContext, Context.Provider, useContext hook, prop drilling problem, context value updates, context with useState, when not to use context
Context API: Shared State Without Prop Drilling
Prop drilling means passing data through layers of components that don't use it just to reach a deeply nested child. Context solves this by broadcasting a value to any component that subscribes, regardless of depth.
Creating and Using Context
import { createContext, useContext, useState } from 'react';
// 1. Create the context
const ThemeContext = createContext('light');
// 2. Provide it at the top level
function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<Layout />
</ThemeContext.Provider>
);
}
// 3. Consume anywhere in the tree
function ThemeToggle() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<button onClick={() => setTheme(t => t === 'light' ? 'dark' : 'light')}>
Current: {theme}
</button>
);
}Context re-renders all consumers when its value changes. To avoid unnecessary re-renders, split contexts by concern — a UserContext, ThemeContext, and SettingsContext are better than one global context. Don't use context as a replacement for all state — keep co-located state local.
