Context API Implementation
Relevant source files
The following files were used as context for generating this wiki page:
- packages/react/src/ReactContext.js
- packages/react-reconciler/src/ReactFiberNewContext.js
- packages/react-reconciler/src/ReactFiberBeginWork.js
- packages/react-reconciler/src/tests/ReactNewContext-test.js
- fixtures/legacy-jsx-runtimes/react-14/cjs/react-jsx-dev-runtime.development.js
- packages/react/src/tests/ReactJSXTransformIntegration-test.js
The React Context API provides a way to pass data through the component tree without having to pass props down manually at every level. It is designed to share data that can be considered "global" for a tree of React components, such as the current authenticated user, theme, or preferred language.
The implementation revolves around a Provider-Consumer model. A Provider component allows components nested under it to subscribe to context changes. A Consumer can be any component that needs to read the value from the context, which can be done either via a Context.Consumer component, the useContext hook, or the legacy readContext API within class components. The core of the mechanism is managed by the React reconciler, which uses the Fiber architecture to efficiently propagate context values and update only the necessary components when a value changes.
Core Concepts & Data Structures
The ReactContext Object
The entry point to the Context API is the React.createContext() function. This function creates a Context object.
Sources: packages/react/src/ReactContext.js:15-38
The structure of this object is central to how the context system works. It holds the default value, the current value, and references to its Provider and Consumer components.
// packages/react/src/ReactContext.js:15-38
export function createContext<T>(defaultValue: T): ReactContext<T> {
const context: ReactContext<T> = {
$$typeof: REACT_CONTEXT_TYPE,
_currentValue: defaultValue,
_currentValue2: defaultValue,
// Used to track how many concurrent renderers this context is in use in.
// During render, every renderer will increment this number when it reaches
// a provider, and decrement it when it leaves. This is used to warn if
// a single context is used by multiple renderers concurrently.
_threadCount: 0,
// These are circular
Provider: (null: any),
Consumer: (null: any),
};
context.Provider = {
$$typeof: REACT_PROVIDER_TYPE,
_context: context,
};
context.Consumer = context;
return context;
}
The following diagram illustrates the structure of the object returned by createContext.
This diagram shows the circular references within the ReactContext object, where Consumer is the context object itself and Provider._context points back to the context object.
Sources: packages/react/src/ReactContext.js:15-38
Context-Related Symbols
React uses special symbols to identify context-related components internally. These symbols are stored in the $$typeof property.
| Symbol Name | Value | Description |
|---|---|---|
REACT_CONTEXT_TYPE | Symbol.for('react.context') | Identifies a Context Consumer object. |
REACT_PROVIDER_TYPE | Symbol.for('react.provider') | Identifies a Context Provider component. |
Sources: fixtures/legacy-jsx-runtimes/react-14/cjs/react-jsx-dev-runtime.development.js:24-25, 43-44
Provider Implementation
When a <Context.Provider> is rendered, the reconciler handles it in the beginWork phase. The updateContextProvider function is responsible for managing the context value stack.
Sources: packages/react-reconciler/src/ReactFiberBeginWork.js
The key steps are:
- Get the new value from the provider's props.
- Push the new value onto the context stack for the given context using
pushProvider. This makes the new value available to all descendants. - Compare the new value with the previous value.
- If the value has changed, it calls
propagateContextChangeto find all consumer fibers in the subtree and schedule an update for them. - Process the children of the provider.
- After the
beginWorkphase for the provider and its children is complete, thecompleteWorkphase pops the value off the stack.
The pushProvider function updates the _currentValue of the context object, making it accessible to consumers deeper in the tree.
Sources: packages/react-reconciler/src/ReactFiberNewContext.js:46-53
Provider Update Flow
The following diagram shows the logic flow within updateContextProvider.
This flowchart illustrates how a Context Provider updates its value and triggers propagation to consumers.
Sources: packages/react-reconciler/src/ReactFiberBeginWork.js:2039-2076, packages/react-reconciler/src/ReactFiberNewContext.js:145-195
Consumer Implementation and Value Propagation
Components consume context values using Context.Consumer, useContext, or readContext. All these methods ultimately rely on the readContext function internally.
Sources: packages/react-reconciler/src/ReactFiberNewContext.js:73-89
readContext
The readContext function is the core mechanism for reading a value from a context. It works by accessing the _currentValue property of the context object, which is maintained by the provider stack.
// packages/react-reconciler/src/ReactFiberNewContext.js:73-89
export function readContext<T>(
context: ReactContext<T>,
): T {
// ...
const value = context._currentValue;
return value;
}
When a component reads a context, it also subscribes to it. The prepareToReadContext function is called before reading, which adds the context to the fiber's dependencies. This ensures that the component will be re-rendered if the context value it depends on changes.
Sources: packages/react-reconciler/src/ReactFiberNewContext.js:55-71
Value Propagation
When a provider's value changes, propagateContextChange is called. This function traverses the fiber tree downwards from the provider to find all consumers that have subscribed to that specific context. For each consuming fiber found, it schedules an update, forcing it to re-render with the new context value.
This propagation respects shouldComponentUpdate: false and React.memo, ensuring that even components that would normally bail out of a re-render will still update if their consumed context value changes.
Sources: packages/react-reconciler/src/ReactFiberNewContext.js:145-195, packages/react-reconciler/src/tests/ReactNewContext-test.js:101-143
The following diagram illustrates how a consumer reads a value and gets updated.
This sequence diagram shows the process of a component reading a context value during render and how a provider update triggers a re-render of the consumer.
Bailout Optimization
If a provider re-renders but its value prop is identical to the previous value (checked with Object.is semantics), the propagateContextChange step is skipped. This prevents unnecessary re-renders of consumers down the tree.
Sources: packages/react-reconciler/src/tests/ReactNewContext-test.js:186-231
The useContext Hook
The useContext hook is the modern, idiomatic way to consume context in function components. It is a thin wrapper around the internal readContext function.
// Simplified from ReactFiberHooks.js
function useContext(Context) {
// ... validation checks ...
return readContext(Context);
}
The hook ensures that the component calling it is subscribed to the context and will re-render when the context value changes. It includes development-only warnings to prevent incorrect usage, such as calling it from a class component or passing Context.Consumer instead of the Context object itself.
Sources: packages/react-reconciler/src/tests/ReactNewContext-test.js:833-855