Skip to main content
Creates a Context object for passing data through the component tree without manually passing props at every level.

Signature

Parameters

T
required
The default value used when a component does not have a matching Provider above it in the tree.

Return Value

Returns a Context<T> object with the following properties:

Description

createContext creates a Context object that allows you to share values between components without explicitly passing props through every level of the tree. The Context object includes:
  • Provider: Component that provides the context value
  • Consumer: Component that consumes the context value
Components that consume context will re-render when the Provider’s value changes.

Implementation

The function is implemented in src/create-context.js:6:

Usage Examples

Basic Context

With Consumer Component

Complex Context Value

Multiple Contexts

With TypeScript

Class Component Consumer

Dynamic Context Updates

Nested Providers

Best Practices

Separate Context Creation

Custom Hook for Context

Avoid Unnecessary Re-renders

Default Value Usage

The default value is used when no Provider is found:

Performance Considerations

  • Context updates trigger re-renders of all consuming components
  • Use multiple contexts to separate concerns and reduce re-renders
  • Memoize context values when they’re computed or include functions
  • Consider using state management libraries for complex state
  • useContext hook - Consume context in function components
  • Component - Class components with contextType
  • Fragment - Group elements without wrapper