Mutability and Effect Inference
Relevant source files
The following files were used as context for generating this wiki page:
- compiler/packages/babel-plugin-react-compiler/src/Inference/MUTABILITY_ALIASING_MODEL.md
- compiler/packages/babel-plugin-react-compiler/src/Inference/InferMutationAliasingEffects.ts
- compiler/packages/babel-plugin-react-compiler/src/Inference/AnalyseFunctions.ts
- compiler/packages/babel-plugin-react-compiler/src/Inference/InferReactivePlaces.ts
- compiler/packages/babel-plugin-react-compiler/src/tests/fixtures/compiler/new-mutability/mutate-after-useeffect.expect.md
- compiler/packages/babel-plugin-react-compiler/src/tests/fixtures/compiler/mutable-lifetime-loops.expect.md
The Mutability and Aliasing system is a fundamental subcomponent of the React Compiler. Its primary purpose is to analyze the code to determine which values can be mutated, how they are aliased, and over what range of instructions these mutations occur. By understanding these data-flow and mutation patterns, the compiler can identify minimal sets of values that change together. This information is then used to group related instructions into reactive scopes, which are the basis for the automatic memoization optimizations that the compiler performs.
This system is crucial for ensuring that the compiler's optimizations are both safe and effective. It prevents common bugs that arise from incorrect memoization, such as failing to re-render when a mutated value should have triggered an update. The analysis is based on a sophisticated model of "effects" that describe how the state of values changes over time.
Sources: compiler/packages/babel-plugin-react-compiler/src/Inference/MUTABILITY_ALIASING_MODEL.md
Core Inference Pipeline
The inference process is broken down into several distinct phases, each building upon the last to form a complete picture of the program's mutation and aliasing behavior.
This diagram shows the high-level flow of the inference pipeline.
Phase 1: InferMutationAliasingEffects
This is the first and foundational phase. It traverses the program's instructions and infers a set of potential mutation and aliasing effects for each one. The process starts by generating candidate effects based on the instruction's semantics and the types of its operands. It then uses abstract interpretation to refine these candidates into the actual effects that apply. For instance, an instruction that would normally have a Capture effect might be downgraded to an ImmutableCapture effect if the value being captured is known to be frozen.
Sources: compiler/packages/babel-plugin-react-compiler/src/Inference/InferMutationAliasingEffects.ts, compiler/packages/babel-plugin-react-compiler/src/Inference/MUTABILITY_ALIASING_MODEL.md
Phase 2: InferMutationAliasingRanges
Building on the effects inferred in the previous phase, this stage determines the "mutable range" for each value in the program. A mutable range is defined by a start and end instruction ID, indicating the window during which a value is considered mutable. This phase constructs a graph representing data flow over time to understand how mutations to one value can affect other values it has been aliased with or captured by.
Sources: compiler/packages/babel-plugin-react-compiler/src/Inference/MUTABILITY_ALIASING_MODEL.md
Phase 3: InferReactiveScopeVariables
The final phase uses the per-place effects and mutable ranges to identify disjoint sets of values that mutate together. All identifiers within such a set are assigned to a unique reactive scope. The mutable range for this scope is expanded to encompass the ranges of all its constituent values. These reactive scopes are the final output that later compiler passes use to generate memoization blocks.
Sources: compiler/packages/babel-plugin-react-compiler/src/Inference/MUTABILITY_ALIASING_MODEL.md, compiler/packages/babel-plugin-react-compiler/src/Inference/InferReactivePlaces.ts
Analysis of Nested Functions
A special consideration is how to handle nested FunctionExpression and ObjectMethod values. The compiler needs to understand their mutation and aliasing semantics to correctly model their behavior when called. The AnalyseFunctions pass calls a dedicated utility, InferFunctionExpressionAliasingEffectsSignature, to determine the publicly observable set of mutation and aliasing effects for these nested functions. This signature is then used by the Apply effect when modeling calls to these functions.
Sources: compiler/packages/babel-plugin-react-compiler/src/Inference/AnalyseFunctions.ts, compiler/packages/babel-plugin-react-compiler/src/Inference/MUTABILITY_ALIASING_MODEL.md
The Effect Model
The entire inference system is built upon a model of "effects" that describe various aspects of mutation, aliasing, and data flow. These effects are categorized based on their function.
Creation Effects
These effects describe the creation of new values.
| Effect | Description - |
| Create | Describes the creation of a new value, such as x = 10. - |
| CreateFunction | Specifically tracks the creation of a function, noting which mutable values it "captures" from its surrounding scope. - |
| Apply | Models the potential creation of a value from a function or method call. The compiler uses the most precise function signature available to determine the effects of the call. |
Sources: compiler/packages/babel-plugin-react-compiler/src/Inference/MUTABILITY_ALIASING_MODEL.md
Aliasing and Data-Flow Effects
These effects describe how references to values are passed around, without necessarily changing the state of the values themselves.
| Effect | Description - |
| Assign | Describes a direct assignment, like x = y. The into value (x) is overwritten. - |
| Alias | Describes a potential, non-exclusive assignment. Used when a function might return one of several inputs, e.g., cond ? a : b. The result may be a or b, but neither overwrites the other. - |
| Capture | A reference to one variable is stored within another. Examples: array.push(value) captures value into array; obj.prop = value captures value into obj. - |
| CreateFrom | A variable is initialized by extracting part of another value, without aliasing the entire value. Examples: x = arr[0], x = obj.prop. - |
| MaybeAlias | Represents potential data flow that the compiler cannot be certain about, such as the return value of an unknown function foo(x). This allows for conservative analysis without producing false-positive errors. |
| ImmutableCapture | Describes immutable data flow. Not currently used for optimizations but is intended for future escape analysis. - |
Sources: compiler/packages/babel-plugin-react-compiler/src/Inference/MUTABILITY_ALIASING_MODEL.md
State-Changing Effects
These effects describe direct changes to the state of a value.
| Effect | Description - |
| Freeze | Marks a reference to a value as immutable. This typically happens when a value is passed as a prop to a JSX element or as an argument to a hook. The compiler assumes that React or other components may now depend on this value, so it should not be mutated further. - |
| Mutate / MutateConditionally | Indicates that a value is mutated directly (e.g., array.push()). It does not affect values that have been captured within it. MutateConditionally is a variant where the mutation may or may not occur. - |
| MutateTransitiveConditionally | Represents an operation that may mutate any aspect of a value, including arbitrarily deep nested values. This is the default assumption for calls to unknown functions. - |
Sources: compiler/packages/babel-plugin-react-compiler/src/Inference/MUTABILITY_ALIASING_MODEL.md
Side Effects and Error Conditions
This category includes effects that represent potential or definite error states.
| Effect | Description - |
| MutateFrozen | An error condition indicating a known mutation of a value that has been frozen. This is always an error. - |
| MutateGlobal | Indicates a known mutation of a global value. This is an error if it occurs during render but is permitted within event handlers or useEffect. - |
| Impure | Indicates a call to impure or side-effecting logic. Similar to MutateGlobal, it is an error during render. - |
Render| Marks a value that is called during render (e.g., JSX tags). This helps detect moreMutateGlobalorImpureeffects. - |
Sources: compiler/packages/babel-plugin-react-compiler/src/Inference/MUTABILITY_ALIASING_MODEL.md
Key Inference Rules
The system follows a set of logical rules to propagate effects through the data-flow graph.
Mutation Propagation
A core principle is that mutating a derived value can mutate the source value, depending on the nature of the derivation.
This diagram illustrates how a Mutate effect on an alias propagates back to the original source.
Mutation of Alias/Assignment/CreateFrom*: If a is an alias of, assigned from, or created from b, then Mutate(a) implies Mutate(b).
- Mutation of Capture: In contrast, if
bis captured intoa(e.g.,a.b = b),Mutate(a)does not implyMutate(b). The mutation affects the containera, not the captured valueb.
Sources: compiler/packages/babel-plugin-react-compiler/src/Inference/MUTABILITY_ALIASING_MODEL.md
The Freeze Effect
A critical rule is how Freeze interacts with aliasing.
- Freeze freezes the reference, not the value: When a reference
yis frozen, it meansyitself cannot be used for mutation. However, the underlying value it points to can still be mutated through other, non-frozen references. Freeze(y)does not implyFreeze(x)even ifyis an alias ofx.- A known mutation on a frozen reference (
Mutate(y)afterFreeze(y)) is an error (MutateFrozen). - A conditional mutation on a frozen reference is a no-op.
This behavior is fundamental to React's programming model. Once you pass a value to a hook or as a prop, you should not mutate it, as React now considers that reference immutable.
Sources: compiler/packages/babel-plugin-react-compiler/src/Inference/MUTABILITY_ALIASING_MODEL.md
Practical Examples
Example 1: Mutation After useEffect
A common mistake is mutating a value after it has been used in a useEffect hook. The inference system correctly identifies this as an error.
// From: mutate-after-useeffect.expect.md
function Component({foo}) {
const arr = [];
// `arr` is used here, which freezes the reference.
useEffect(() => {
arr.push(foo);
}, AUTODEPS);
// This is an error: attempting to mutate a frozen reference.
arr.push(2);
return arr;
}
The compiler will report a MutateFrozen error because arr was captured by useEffect, which applies a Freeze effect to it. The subsequent arr.push(2) is an attempt to mutate this frozen reference.
Example 2: Complex Aliasing in Loops
The system can track aliasing through complex control flow, like loops, to understand the lifetime of mutable values.
// From: mutable-lifetime-loops.expect.md
function testFunction(props) {
let a = {};
let b = {};
let c = {};
let d = {};
while (true) {
let z = a;
a = b;
b = c;
c = d;
d = z;
mutate(a, b); // `a` and `b` are mutated
if (cond(a)) {
break;
}
}
// At this point, a, b, c, and d are all considered mutable because
// they have all been aliased by `d` at some point, which is mutated later.
mutate(d, null);
return {a, b, c, d};
}
In this example, all variables (a, b, c, d) are part of the same reactive scope. Even though some appear to be read-only after the loop, the inference engine understands that they all alias the same set of underlying objects that are mutated throughout the function's execution.
Conclusion
The Mutability and Effect Inference system is a cornerstone of the React Compiler's ability to perform automatic and safe memoization. By building a detailed model of how values are created, aliased, and mutated, it provides the necessary foundation for subsequent optimization passes to understand what can be memoized without breaking the rules of React or introducing subtle bugs. This allows developers to write simple, declarative components while relying on the compiler to handle performance optimizations.
Sources: compiler/packages/babel-plugin-react-compiler/src/Inference/MUTABILITY_ALIASING_MODEL.md