Using the babel-plugin-react-compiler
Relevant source files
The following files were used as context for generating this wiki page:- compiler/packages/babel-plugin-react-compiler/src/Babel/BabelPlugin.ts
- compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Options.ts
- compiler/packages/react-compiler-runtime/src/index.ts
- compiler/packages/react-compiler-healthcheck/src/checks/reactCompiler.ts
- compiler/packages/react-mcp-server/src/index.ts
- compiler/apps/playground/components/Editor/EditorImpl.tsx
- compiler/packages/babel-plugin-react-compiler/package.json
The babel-plugin-react-compiler is a Babel plugin that automatically memoizes React components and hooks. Its primary purpose is to improve application performance by reducing unnecessary re-renders without requiring manual memoization APIs like useMemo or useCallback. The compiler analyzes component code and injects memoization logic, simplifying the codebase and making it more maintainable.
This plugin is a core part of the React toolchain, used in development environments like the React Playground, and for performing automated code analysis through tools like the React Compiler Healthcheck. It integrates with Babel to transform source code during the build process.
Core Functionality and Integration
The plugin operates within the Babel ecosystem. It takes JavaScript or TypeScript code, parses it into an Abstract Syntax Tree (AST), and then transforms this AST to inject optimization code. The final AST is then converted back into optimized JavaScript code.
The basic integration flow is as follows:
- Parsing: The source code is parsed into an AST using a parser like
@babel/parserorhermes-parser. The plugin supportstypescriptandjsxsyntax. - Transformation: The
transformFromAstSyncfunction from@babel/coreis called, withbabel-plugin-react-compilerlisted in the plugins array. - Code Generation: The transformed AST is used to generate the final, optimized code.
Sources: compiler/packages/react-compiler-healthcheck/src/checks/reactCompiler.ts:63-78, compiler/apps/playground/components/Editor/EditorImpl.tsx:70-87
This diagram illustrates the high-level transformation process.
Configuration
The plugin's behavior can be customized through a PluginOptions object.
Sources: compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Options.ts, compiler/packages/react-compiler-healthcheck/src/checks/reactCompiler.ts:40-44, compiler/packages/react-mcp-server/src/index.ts:153-173
| Option | Type | Description | Default |
|---|---|---|---|
compilationMode | 'infer' | 'all' | Determines which functions to compile. 'infer' compiles components and hooks, while 'all' compiles all functions. | 'infer' |
panicThreshold | 'none' | 'critical_errors' | Sets the error level at which the compiler will panic and stop. | 'critical_errors' |
logger | Logger | An object to log compiler events, such as successes, errors, and diagnostics. | null |
noEmit | boolean | If true, the plugin will run but not produce any output code. Useful for analysis tools. | false |
environment | EnvironmentConfig | Configuration for the target environment, including custom hook definitions. | {} |
Logger
The logger option is crucial for diagnostics and tooling. It provides hooks to receive events from the compiler.
The logEvent function receives events of different kinds:
CompileSuccess: Fired when a function is successfully compiled.CompileError: Fired when a compilation fails due to an error in the user's code.CompileDiagnostic: Fired for non-critical issues or suggestions.PipelineError: Fired for internal compiler errors.
This diagram shows the flow of events to the logger.
Compilation Process and Output
When the compiler successfully optimizes a component, it injects code that relies on a runtime library.
Successful Compilation
A successful compilation results in:
- An import of the
react-compiler-runtimemodule. Typically,import { c as _c } from "react/compiler-runtime";. - The creation of a memoization cache at the start of the component body:
const $ = _c(n);, wherenis an integer representing the cache size.
Sources: compiler/packages/react-mcp-server/src/index.ts:455-458, compiler/packages/react-compiler-runtime/src/index.ts
Compiler Pipeline
The compilation process involves several internal passes. The logger can be configured to log the Intermediate Representation (IR) at different stages for debugging purposes.
Key pipeline stages include:
- HIR (High-level IR): An initial representation of the code.
- ReactiveFunction: A representation showing reactive scopes and dependencies.
The logIR function can be passed to the logger to capture and print the output of these stages.
This diagram shows a simplified view of the compiler's internal pipeline.
Error Handling and Diagnostics
The compiler is designed to provide detailed feedback when it cannot optimize code. These are reported as "bailouts" or diagnostics.
Error Severity
Errors are categorized by severity, which helps tools decide how to report them.
| Severity | Description |
|---|---|
InvalidReact | The code violates the Rules of React. These are often actionable by the developer. |
InvalidJS | The code uses JavaScript patterns that are not currently supported by the compiler. |
Todo | The compiler encountered a pattern it doesn't yet support but may in the future. |
Invariant | An internal error occurred in the compiler. |
InvalidConfig | The plugin options are configured incorrectly. |
CannotPreserveMemoization | The compiler cannot preserve existing manual memoization (useMemo/useCallback). |
Sources: compiler/packages/react-compiler-healthcheck/src/checks/reactCompiler.ts:46-57, compiler/apps/playground/components/Editor/EditorImpl.tsx:28-34
When a CompileError event is logged, it includes a detail object with the reason, severity, and source location of the error. For example, the react-mcp-server uses this information to report bailouts and suggest fixes, such as removing manual useMemo/useCallback wrappers.
Sources: compiler/packages/react-mcp-server/src/index.ts:100-103, 163-172
Runtime (react-compiler-runtime)
The babel-plugin-react-compiler relies on a small runtime package, react-compiler-runtime, to manage the memoization cache. The compiled code will contain imports from this package.
The primary exports are:
c: A function aliased as_cin compiled code. It is called at the beginning of a component to create and initialize the memoization cache.i: A function aliased as_i. It is used to invalidate the cache.
// compiler/packages/react-compiler-runtime/src/index.ts
// create a cache
export function c(size: number) {
// ...
}
// invalidate a cache
export function i(cache: Array<any>) {
// ...
}
Sources: compiler/packages/react-compiler-runtime/src/index.ts
The compiled output of a component will look something like this, demonstrating the use of the runtime:
import {c as _c} from 'react/compiler-runtime';
function MyComponent(props) {
const $ = _c(2); // Creates a cache of size 2
// ... memoized logic using $
return <div>...</div>;
}
Sources: compiler/packages/react-mcp-server/src/index.ts:455-458