Context API Pattern

Overview

The Context API in React provides a way to share values like themes, user data, or other global state between components without having to explicitly pass props through every level of the component tree. It's designed to solve the "prop drilling" problem, where data needs to be passed through many nested components.

Example

This example demonstrates a theme context that lets components access and update the current theme without prop drilling. Click the button to toggle between light and dark themes.

Themed Header

Current theme: light

Footer with light theme

Code Implementation

// ThemeContext.tsx
import React, { createContext, useState, ReactNode } from "react";

// Define the shape of the context
type ThemeContextType = {
  theme: string;
  toggleTheme: () => void;
};

// Create the context with default values
export const ThemeContext = createContext<ThemeContextType>({
  theme: "light",
  toggleTheme: () => {},
});

// Create a provider component
export const ThemeProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [theme, setTheme] = useState("light");

  const toggleTheme = () => {
    setTheme(prevTheme => (prevTheme === "light" ? "dark" : "light"));
  };

  // The context value that will be passed to consuming components
  const contextValue = {
    theme,
    toggleTheme,
  };

  return (
    <ThemeContext.Provider value={contextValue}>
      {children}
    </ThemeContext.Provider>
  );
};

// Usage in components:
// const { theme, toggleTheme } = useContext(ThemeContext);

Key Benefits

  • Avoid prop drilling through multiple component layers
  • Create global or semi-global state accessible to many components
  • Maintain component encapsulation while sharing state
  • Simplify component composition and reduce coupling
  • Better organization of shared state and state management