Capítulo 80 de 116

Chapter 80: createContext

Core Idea

createContext(defaultValue) creates the Context object that a provider supplies a value for and useContext reads from — the constructor half of the Context mechanism whose usage was covered in Ch 32/50.

Key Concepts

  • Signature: const SomeContext = createContext(defaultValue) — returns an object with a Provider-capable component (in modern React, the Context object itself is used directly as <SomeContext value={...}>) and serves as the identity useContext matches against.
  • defaultValue is the fallback, used only when a consumer calls useContext(SomeContext) with no matching provider anywhere above it in the tree — not a "default until the real value loads" mechanism, and not used at all once any provider is present above a given consumer.
  • Module-level, created once: a Context is typically created at module scope (outside any component) and exported, so every file that needs to provide or consume it imports the same object — creating a new Context inside a component body on every render would break identity matching entirely.
  • Typed contexts (TypeScript): createContext<T>(defaultValue) carries the value's type through to every useContext call site automatically — a common reason defaultValue is given a realistic shape (or null with the consuming code guarding against it) rather than an arbitrary placeholder.

Code Examples

// theme-context.js — created once at module scope, imported wherever needed
export const ThemeContext = createContext('light');
  • What it demonstrates: the module-level creation pattern that makes the same Context object available to both providers and consumers across the app.

Key Takeaways

  1. Create a Context exactly once, at module scope — never inside a component body, or every render would produce a distinct, unmatched Context identity.
  2. defaultValue only applies with zero providers above the consumer — don't rely on it as a general fallback while a real provider is still initializing.
  3. Export the Context object from a dedicated module so provider and consumer files share the same identity via import.

Connects To

  • Ch 32 (Passing Data Deeply with Context): the conceptual walkthrough this constructor supports.
  • Ch 50 (useContext): the read side of the Context this function creates.