0Pricing
Frontend Academy · Lesson

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

  1. useContext for Global State
  2. useReducer for Complex State
  3. useMemo and useCallback for Performance
  4. Custom Hooks: Extracting Reusable Logic
← Back to Frontend Academy