Understanding Reactive Scopes
Relevant source files
The following files were used as context for generating this wiki page:
- compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/BuildReactiveFunction.ts
- compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/InferReactiveScopeVariables.ts
- compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/CodegenReactiveFunction.ts
- compiler/packages/babel-plugin-react-compiler/src/HIR/HIR.ts
- compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/index.ts
- packages/react-reconciler/src/tests/ReactScope-test.internal.js
Reactive Scopes are a core concept within the React Compiler (babel-plugin-react-compiler). They represent memoizable units of computation within a React component or hook. The primary purpose of identifying these scopes is to enable the compiler to automatically wrap them in memoization checks, preventing unnecessary re-executions and re-renders, thus improving application performance without manual useMemo or useCallback hooks.
The process involves transforming a function's High-Level Intermediate Representation (HIR) into a ReactiveFunction structure. This structure contains a tree of reactive blocks and scopes, each with its own set of dependencies. The compiler then analyzes these dependencies to determine when a scope needs to be re-evaluated. Finally, it generates optimized JavaScript code that uses a runtime cache to skip work when dependencies have not changed.
Core Data Structures
The concept of Reactive Scopes is built upon a tree-shaped data model that represents the reactive parts of a function. The top-level structure is the ReactiveFunction.
Sources: compiler/packages/babel-plugin-react-compiler/src/HIR/HIR.ts:40-60, compiler/packages/babel-plugin-react-compiler/src/HIR/HIR.ts:912-969
Key Data Types
| Type | Description | File |
|---|---|---|
ReactiveFunction | Represents a React function (component or hook) with a body composed of ReactiveBlocks. It holds parameters, async/generator status, and environment details. | HIR/HIR.ts:40-48 |
ReactiveScope | The core of memoization. It defines a range of computation, its dependencies, the values it declares, and any reassignments it performs. | HIR/HIR.ts:912-969 |
ReactiveBlock | An array of ReactiveStatements, which can be instructions, terminals, or nested scope blocks. | HIR/HIR.ts:66-68 |
ReactiveInstruction | A single, non-branching computation, such as an assignment or a function call, that produces a value (lvalue). | HIR/HIR.ts:80-86 |
ReactiveTerminal | A control-flow statement like if, switch, or return that terminates a ReactiveBlock. | HIR/HIR.ts:121-147 |
ReactiveScopeDependency | Represents a dependency of a ReactiveScope, consisting of an identifier and an optional property access path. | HIR/HIR.ts:981-990 |
Data Structure Relationships
The following diagram illustrates the relationships between the main data structures in the Reactive Scopes model.
This diagram shows how a ReactiveFunction is composed of blocks, which in turn contain statements, scopes, and instructions.
Sources: compiler/packages/babel-plugin-react-compiler/src/HIR/HIR.ts:40-147, 912-990
The Reactive Scope Compilation Pipeline
The React Compiler processes a function's HIR through several stages to identify and codegen reactive scopes. This pipeline transforms the control-flow graph representation into a reactive tree, infers dependencies, and finally generates optimized JavaScript.
This diagram shows the high-level flow of the Reactive Scope compilation process.
1. Building the Reactive Function
The first step is to convert the HIRFunction (a control-flow graph) into a ReactiveFunction (a tree structure).
The buildReactiveFunction function is the entry point for this process. It traverses the HIR, block by block, and converts HIR instructions and terminals into their Reactive counterparts. It reconstructs the program's structure, such as if statements and loops, into a nested tree of ReactiveBlocks.
Sources: compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/BuildReactiveFunction.ts:40-44
2. Inferring Scope Variables
Once the ReactiveFunction tree is built, the inferReactiveScopeVariables pass walks this tree to determine the precise dependencies for each ReactiveScope.
It operates in two phases:
- Downward Pass (Collecting reads): It traverses the tree from the root downwards, identifying all variables that are read within each scope.
- Upward Pass (Propagating dependencies): It then walks back up the tree. For each scope, it resolves the reads to their original declarations. If a variable is declared outside the current scope, it becomes a dependency of that scope. These dependencies are then propagated up to parent scopes.
This process ensures that each scope is associated with the minimal set of variables that, if changed, would require the scope's computation to be re-executed.
The following diagram illustrates how dependency inference works.
This sequence shows the traversal and dependency propagation performed by inferReactiveScopeVariables.
3. Code Generation
After all transformations and optimizations are complete, the codegenFunction is responsible for converting the ReactiveFunction back into a standard JavaScript Abstract Syntax Tree (AST).
Key responsibilities of this phase include:
- Introducing a call to the
useMemoCachehook at the beginning of the function to create a cache array. - For each
ReactiveScope, generating anifstatement that checks if the scope's dependencies have changed by comparing them to values stored in the cache. - Placing the instructions from the
ReactiveScopeinside theifblock. - Updating the cache with the new dependency values after the scope's code has executed.
Sources: compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/CodegenReactiveFunction.ts:60-69
A simplified example of the generated code structure:
// compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/CodegenReactiveFunction.ts
function MyComponent(props) {
// 1. Cache is created
const $ = useMemoCache(2);
let x;
// 2. Dependencies are checked against the cache
if ($[0] !== props.a) {
// 3. Scope is executed if dependencies changed
x = compute(props.a);
// 4. Cache is updated
$[0] = props.a;
$[1] = x;
} else {
// 5. Value is retrieved from cache
x = $[1];
}
return <div>{x}</div>;
}
This snippet illustrates the basic memoization pattern generated by the codegenFunction for a reactive scope.
Sources: compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/CodegenReactiveFunction.ts:311-354
Runtime Scopes: React.unstable_Scope
Separate from the compiler's "Reactive Scopes" is a runtime API, React.unstable_Scope. This feature is not directly for memoization but provides a mechanism to query for DOM nodes within a component subtree, acting as a boundary for DOM queries.
This API is exposed on the React object when the enableScopeAPI feature flag is true. It is a component that can be rendered in the tree and accepts a ref. This ref can then be used to query for nodes contained within the <Scope> boundary.
Key methods on the Scope ref instance include:
DO_NOT_USE_queryAllNodes(queryFn): Returns all host nodes within the scope that match thequeryFn.DO_NOT_USE_queryFirstNode(queryFn): Returns the first host node within the scope that matches thequeryFn.containsNode(node): Checks if a given host node is within the scope.getChildContextValues(context): Retrieves values fromContext.Providers within the scope.
Sources: packages/react-reconciler/src/tests/ReactScope-test.internal.js:23-26, 44-53, 140-149
Summary
Reactive Scopes are a fundamental part of the React Compiler's optimization strategy. By transforming a function's HIR into a tree of ReactiveFunctions, the compiler can precisely infer dependencies for memoizable blocks of code. The pipeline builds this tree, infers dependencies, and then generates highly optimized JavaScript that avoids re-computation, leading to significant performance gains automatically. This compiler-level concept is distinct from the React.unstable_Scope runtime API, which is designed for querying DOM nodes within a boundary.