useContext
Sharing state across the component tree without prop drilling
Skills taught: react.createContext, react.useContext, react.context-provider, react.context-pattern
Context: sharing state across the tree
// Step 1: Create the context
const ThemeContext = createContext('light'); // default value if no Provider above
// Step 2: Create a Provider component (good pattern: keep state + context together)
function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
// Custom hook for convenience
function useTheme() {
return useContext(ThemeContext);
}
// Step 3: Consume anywhere in the tree — no props needed!
function ThemeToggle() {
const { theme, setTheme } = useTheme();
return (
<button onClick={() => setTheme(t => t === 'light' ? 'dark' : 'light')}>
{theme === 'light' ? '🌙 Dark Mode' : '☀️ Light Mode'}
</button>
);
}
function Page() {
const { theme } = useTheme();
const isDark = theme === 'dark';
return (
<div style={{
background: isDark ? '#0e1116' : '#fff',
color: isDark ? '#e2e8f0' : '#111',
padding: '16px', borderRadius: '8px', transition: 'all 0.3s'
}}>
<h2>Theme: {theme}</h2>
<p>This page reads the theme from context.</p>
<ThemeToggle />
</div>
);
}
function App() {
return (
<ThemeProvider>
<Page /> {/* Page and all its children can access ThemeContext */}
</ThemeProvider>
);
}
Frequently Asked Questions
Is Context a replacement for Redux?
For small-to-medium apps, yes — Context + useReducer can handle most global state needs without the Redux boilerplate. For large apps with many independent state slices, high-frequency updates, or needs like time-travel debugging, Redux (or Zustand) has better performance characteristics. Context re-renders all consumers on every change; external stores allow selective subscriptions.