useContext for Global State
Create a Context, wrap a subtree with its Provider, and consume the value with useContext to share theme or auth state without prop drilling.
The Problem with Prop Drilling
Prop drilling means passing data through many intermediate components that don't use it, just to reach a deeply nested child. Context solves this by making a value available to any component in the tree without explicit passing.
Creating a Context
createContext(defaultValue) creates a Context object. The default value is used when a component reads the context without a matching Provider above it.
import { createContext } from 'react';
interface ThemeContextType {
theme: 'light' | 'dark';
toggleTheme: () => void;
}
const ThemeContext = createContext<ThemeContextType>({
theme: 'light',
toggleTheme: () => {}
});All lessons in this course
- useContext for Global State
- useReducer for Complex State
- useMemo and useCallback for Performance
- Custom Hooks: Extracting Reusable Logic