Lesson 6 of 11
useContext - Avoiding Prop Drilling
useContext solves prop drilling - passing data through many component layers via props. But it has an important performance characteristic: every consumer re-renders when the context value changes. Understanding context splitting and when to use Zustand instead is key.
Creating and Using Context
import { createContext, useContext, useState, useMemo } from 'react';
// 1. Create typed context with a default that throws - catches missing providers early
interface ThemeContextValue {
theme: 'light' | 'dark';
toggleTheme: () => void;
}
const ThemeContext = createContext<ThemeContextValue | undefined>(undefined);
// Custom hook - provides type safety and better error message
export function useTheme(): ThemeContextValue {
const ctx = useContext(ThemeContext);
if (!ctx) throw new Error('useTheme must be used within ThemeProvider');
return ctx;
}
// 2. Provider - wrap at the highest level that needs this context
function ThemeProvider({ children }: { children: React.ReactNode }) {
const [theme, setTheme] = useState<'light' | 'dark'>('light');
// Memoize the context value - prevents all consumers re-rendering when
// an unrelated state in the provider changes
const value = useMemo(
() => ({
theme,
toggleTheme: () => setTheme(t => t === 'light' ? 'dark' : 'light'),
}),
[theme]
);
return (
<ThemeContext.Provider value={value}>
{children}
</ThemeContext.Provider>
);
}
// 3. Consume - any component in the tree can call useTheme()
function ThemeToggle() {
const { theme, toggleTheme } = useTheme();
return (
<button onClick={toggleTheme}>
{theme === 'light' ? '๐ Dark' : 'โ๏ธ Light'}
</button>
);
}Context Splitting - The Key Performance Pattern
// โ One big context - EVERY consumer re-renders on ANY change
const AppContext = createContext({
user: null, // changes rarely
theme: 'light', // changes rarely
notifications: [], // changes FREQUENTLY (real-time)
});
// A component only using user re-renders on notification changes too - wasteful
// โ
Split by update frequency - consumers only re-render for their context
const UserContext = createContext<User | null>(null);
function UserProvider({ children }) { ... }
const ThemeContext = createContext<ThemeValue>(defaultTheme);
function ThemeProvider({ children }) { ... }
const NotificationContext = createContext<Notification[]>([]);
function NotificationProvider({ children }) { ... }
// Compose providers
function AppProviders({ children }: { children: React.ReactNode }) {
return (
<UserProvider>
<ThemeProvider>
<NotificationProvider>
{children}
</NotificationProvider>
</ThemeProvider>
</UserProvider>
);
}
// When to use Zustand instead of Context:
// ๐ Context: low-frequency changes (theme, auth user, locale)
// ๐ Zustand: frequent updates, many consumers, complex state (cart, real-time data)Common Mistakes - useContext
- Not memoizing the context value - every time the provider re-renders, a new context object is created, causing all consumers to re-render; always wrap with useMemo
- Using context for everything - global state through context can cause performance issues at scale; use Zustand or TanStack Query for server state and frequently updating data
- Creating context without a custom hook - consumers need to remember to check for undefined and access the right context; a custom hook hides this and provides better error messages
- Provider placed too low in the tree - if the provider is below components that need the context, they get the default value (usually undefined) instead of the provided value
Tip
Tip
Practice useContext Avoiding Prop Drilling in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for useContext - Avoiding Prop Drilling
Practice Task
Note
Practice Task - (1) Write a working example of useContext Avoiding Prop Drilling from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with useContext Avoiding Prop Drilling is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Key Takeaways
- useContext solves prop drilling - passing data through many component layers via props.
- Not memoizing the context value - every time the provider re-renders, a new context object is created, causing all consumers to re-render; always wrap with useMemo
- Using context for everything - global state through context can cause performance issues at scale; use Zustand or TanStack Query for server state and frequently updating data
- Creating context without a custom hook - consumers need to remember to check for undefined and access the right context; a custom hook hides this and provides better error messages
Finished this lesson?