Context API 🌐
Context is React’s built-in intercom system: provide data once, consume it anywhere below without threading props through every level.
Create + Provide 🎁
const ThemeContext = createContext<{ mode: 'light' | 'dark'; toggle(): void } | null>(null);
export function ThemeProvider({ children }: { children: React.ReactNode }) {
const [mode, setMode] = useState<'light' | 'dark'>('light');
const value = useMemo(() => ({ mode, toggle: () => setMode(m => (m === 'light' ? 'dark' : 'light')) }), [mode]);
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}Consume 📞
export function ThemeSwitcher() {
const ctx = useContext(ThemeContext);
if (!ctx) throw new Error('ThemeProvider missing');
return <button onClick={ctx.toggle}>Mode: {ctx.mode}</button>;
}Next.js Placement Tips 🗺️
- Wrap layout components (
app/layout.tsx) to make context available across routes. - For server components, pass data via props; context is client-only unless you use the new server-context APIs.
- Memoize context values to avoid unnecessary re-renders downstream.
Use Cases 🎯
- Theme toggles, auth/session info, feature flags.
- Avoid prop drilling in deeply nested trees (nav → sidebar → button).
- Combine with
useReducerfor mini state machines.
Analogy: Context is a subway line running beneath your component city—any station (component) can hop on without building new tunnels (prop chains).
Use it sparingly; too much global state can make logic harder to trace. Balance context with plain props and custom hooks. ⚖️
Last updated on