Skip to main content

Overview

Context provides a way to pass data through the component tree without having to pass props down manually at every level. It’s designed to share data that can be considered “global” for a tree of React components.

Creating Context

Use createContext to create a context object. The context comes with a Provider and Consumer.

API Signature

From packages/react/src/ReactContext.js:14:
The function returns a context object with the following structure:

Using Context with Provider

The Provider component allows consuming components to subscribe to context changes.

Consuming Context

The useContext hook is the modern way to consume context values.
From packages/react/src/ReactHooks.js:56, calling useContext(Context.Consumer) is not supported:
Always pass the Context object directly, not Context.Consumer.

With Context.Consumer (Legacy)

The Consumer component uses a render prop pattern:

Practical Examples

Theme Context

Authentication Context

Multiple Contexts

You can use multiple contexts in a single component:

Default Values

The default value is used when a component doesn’t have a matching Provider above it:

Updating Context Values

Context value updates trigger re-renders of all consuming components. For performance-critical applications, consider:
  1. Splitting contexts by update frequency
  2. Using composition to limit re-renders
  3. Memoizing context values with useMemo

Context Internal Implementation

From packages/react/src/ReactContext.js:18:
React maintains separate _currentValue and _currentValue2 fields to support multiple concurrent renderers (e.g., React DOM and React Native running simultaneously).

Best Practices

  1. Create custom hooks: Wrap useContext in custom hooks for better error handling and type safety
  2. Split contexts: Don’t put all global state in one context. Split by domain or update frequency
  3. Provide meaningful defaults: Default values should be valid states, not just null
  4. Memoize context values: Use useMemo to prevent unnecessary re-renders
  5. Document context shape: Use TypeScript or JSDoc to document the context structure

When to Use Context

Context is ideal for:
  • Theme data (color, font, etc.)
  • Current authenticated user
  • Locale/language preferences
  • UI state (modals, tooltips)
Context may not be ideal for:
  • Frequently changing data (use state management libraries)
  • Data that only a few components need (use props)
  • Performance-critical updates (consider alternatives)

See Also

  • Hooks - Learn about useContext and other hooks
  • Component API - Component lifecycle and APIs