Lesson 28 +10 XP

Intro to Context API & createContext

Intro to Context API & createContext

Passing props down through multiple layers of intermediate components (known as Prop Drilling) can quickly make code verbose and fragile. React's Context API solves prop drilling by allowing data to be broadcast to any component in the tree without manually passing props at every level.

The Prop Drilling Problem

Imagine a scenario where a top-level App component holds theme data that a deeply nested ThemeToggleButton needs.

[ App (holds theme) ] 
       │ (props)
       ▼
  [ Header ] 
       │ (props)
       ▼
 [ Navigation ] 
       │ (props)
       ▼
[ ThemeToggleButton (uses theme) ]

Neither Header nor Navigation actually use the theme prop—they are merely acting as pass-through couriers. This is Prop Drilling.

What is the Context API?

The Context API creates a global-like data pipeline for a tree of React components. Components can "subscribe" directly to context data regardless of how deeply nested they are.

[ ThemeContext ] ──────────── (direct broadcast) ────────────► [ ThemeToggleButton ]

Creating Context with createContext

Import createContext from react and initialize a new Context object. You can pass a default fallback value as an argument.

// src/context/ThemeContext.js
import { createContext } from 'react';

// Create context with optional default value
export const ThemeContext = createContext('light');

Common Use Cases for Context

Context is ideal for global or semi-global data shared by many components across an application:

  • User authentication state (currentUser, login status)
  • UI themes (Light / Dark mode)
  • App localization (language preference, currency, translations)
  • Shopping cart contents in e-commerce apps

Summary & TL;DR

  • Prop Drilling happens when props are passed through uninterested intermediate components.
  • The Context API allows components to share data directly across the component tree.
  • Use createContext(defaultValue) to initialize a Context object.