new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

React · API reference · all subjects

react-compiler

102 notes in this subject, read out of this brain and free to use. This is page 1 of 2.

Troubleshooting: Cannot find module 'react-compiler-runtime'

If users see a 'Cannot find module react-compiler-runtime' error, ensure the runtime is listed in dependencies not devDependencies, check that the bundler includes the runtime in the output, and verify the package is published to npm with the library.

Package.json configuration for libraries with React Compiler

Libraries using React Compiler should include react-compiler-runtime in the dependencies field with a version constraint like ^1.0.0, and list react in peerDependencies with a version range supporting the target versions, such as ^17.0.0 || ^18.0.0 || ^19.0.0

Install react-compiler-runtime for backward compatibility

For libraries supporting React versions below 19, install react-compiler-runtime as a direct dependency using: npm install react-compiler-runtime@latest. It should be listed in the dependencies field of package.json, not devDependencies.

Benefits of shipping compiled React library code

Shipping compiled library code provides performance improvements for all users even if they are not using React Compiler yet, requires no configuration by users as optimizations work out of the box, and ensures consistent behavior across all users regardless of their build setup.

Install babel-plugin-react-compiler for library compilation

Install babel-plugin-react-compiler as a dev dependency using: npm install -D babel-plugin-react-compiler@latest

Configure babel-plugin-react-compiler in babel.config.js

Add 'babel-plugin-react-compiler' to the plugins array in babel.config.js to enable compilation during the build process.

Set target React version in React Compiler configuration

Configure the target field in the React Compiler options with the minimum React version your library supports, for example: target: '17'

Testing strategy for compiled library code

Test your library both with and without compilation to ensure compatibility. Run your existing test suite against the compiled code, and create a separate test configuration that bypasses the compiler to catch any issues that might arise from the compilation process.

Troubleshooting: Library errors in React 17 or 18

If a compiled library throws errors in React 17 or 18, verify that react-compiler-runtime is installed as a dependency, check that the target configuration matches the minimum supported React version, and ensure the runtime package is included in the published bundle.

Resolving Babel plugin conflicts with React Compiler

If compilation conflicts with other Babel plugins, place babel-plugin-react-compiler early in the plugin list, disable conflicting optimizations in other plugins, and test the build output thoroughly.

compilationMode troubleshooting: hooks must call React hooks

In 'infer' mode, a function named like a hook (with 'use' prefix) will only be compiled if it actually calls React hooks. A function named 'useData' that only calls window.localStorage.getItem will not be compiled, but one that calls useState will be.

compilationMode option type and default

The compilationMode option is a configuration property for the React Compiler. Its type is a union of string literals: 'infer' | 'syntax' | 'annotation' | 'all'. The default value is 'infer'.

compilationMode 'annotation' mode behavior

In 'annotation' mode, only functions explicitly marked with the 'use memo' directive are compiled. This mode is ideal for incremental adoption.

compilationMode 'syntax' mode behavior

In 'syntax' mode, only components and hooks that use Flow's component and hook syntax are compiled. This mode requires Flow and will not work with TypeScript.

compilationMode 'all' mode behavior

In 'all' mode, all top-level functions are compiled. This mode is not recommended because it may compile non-React functions and negatively impact performance by compiling utility functions.

compilationMode 'use no memo' directive behavior

Regardless of compilation mode, functions with the 'use no memo' directive are always skipped from compilation.

compilationMode example: infer mode with various functions

In 'infer' mode, the following code demonstrates which functions are compiled: a function named Button (PascalCase) that returns JSX is compiled, a function named useCounter that calls useState is compiled, a function with an explicit 'use memo' directive is compiled, and a function named calculateTotal that is not a component/hook pattern is not compiled.

compilationMode example: annotation mode

In 'annotation' mode, only functions explicitly marked with 'use memo' are compiled. A function named ExpensiveList with the 'use memo' directive will be compiled, while a function named NormalComponent without the directive will not be compiled.

compilationMode example: Flow syntax mode

When using 'syntax' mode with Flow, functions defined with Flow's component syntax (component keyword) and hook syntax (hook keyword) are compiled. Regular function syntax is not compiled in this mode.

compilationMode example: opting out with 'use no memo'

Functions can opt out of compilation by including the 'use no memo' directive. This directive prevents compilation regardless of the compilation mode. This is useful for components with side effects that should not be memoized.

compilationMode troubleshooting: infer mode naming requirements

In 'infer' mode, components must use PascalCase naming to be detected. Functions with lowercase names will not be compiled even if they create JSX. For example, a function named 'button' will not be compiled, but 'Button' will be.

compilationMode 'infer' mode behavior

In 'infer' mode (the default), the compiler uses intelligent heuristics to identify React components and hooks. It compiles: functions explicitly annotated with the 'use memo' directive, and functions that are named like components (PascalCase) or hooks (use prefix) AND create JSX and/or call other hooks. The 'infer' mode requires functions to follow React naming conventions to be detected.

React 19 default compiler configuration

For React 19 applications, the React Compiler works without any configuration. You can add 'babel-plugin-react-compiler' to the Babel plugins array with no additional options and it will use sensible defaults.

React 17/18 compiler setup requires runtime

When targeting React 17 or 18, you must install the react-compiler-runtime package as a dependency and set the target option to '17' or '18' respectively in the compiler configuration.

Incremental adoption with compilationMode annotation

To incrementally adopt the React Compiler, you can set compilationMode to 'annotation' to only compile functions marked with 'use memo', allowing you to start with specific directories and expand gradually.

babel-plugin-react-compiler setup

The React Compiler is configured as a Babel plugin named 'babel-plugin-react-compiler'. It is added to the plugins array in babel.config.js with optional compiler options as a second parameter.

compilationMode option

The compilationMode option controls the strategy for selecting functions to compile. It accepts values like 'annotation' which only compiles functions marked with 'use memo'. This option determines what the compiler optimizes and how it selects components and hooks to compile.

target option for React version

The target option specifies which React version you are using. It accepts values '17', '18', or '19'. When targeting React 17 or 18, you must also install the react-compiler-runtime package separately.

panicThreshold option

The panicThreshold option determines how the compiler responds to code that doesn't follow the Rules of React. Setting it to 'none' will skip components with errors instead of failing the build, which is recommended for production environments.

logger option

The logger option provides custom logging for compilation events. It accepts an object with a logEvent function that receives filename and event parameters. The event object has a kind property that indicates the type of compilation event, such as 'CompileSuccess'.

gating option for feature flags

The gating option enables runtime feature flags for A/B testing or gradual rollouts. It accepts an object with source and importSpecifierName properties, where source specifies the module to import feature flags from and importSpecifierName specifies the name of the import to use.

Module-level directive placement

Module-level directives are placed at the very top of a file, before all imports and functions, to affect all functions in that module. Function-level directives can override module-level directives. Example: "use memo"; function Component1() { return <div>Compiled</div>; } function Component2() { "use no memo"; return <div>Not compiled</div>; }

Compilation mode interaction with directives

Directives behave differently depending on compilationMode: in annotation mode, only functions with "use memo" are compiled; in infer mode, the compiler decides what to compile and directives override those decisions; in all mode, everything is compiled and "use no memo" can exclude specific functions.

Gradual adoption pattern for React Compiler

When adopting React Compiler in a large codebase, start with annotation mode and opt in stable components with "use memo". Later, switch to infer mode and opt out problematic components with "use no memo" while fixing underlying issues.

Directive best practice: use sparingly

Directives are escape hatches and should be used sparingly. Prefer configuring the compiler at the project level through babel-plugin-react-compiler configuration rather than using directives in code.

Directive best practice: document usage

Always include comments explaining why a directive is used in the code. For example, document which specific issue prompted an opt-out or provide context about why a function needs special handling.

Directive best practice: plan for removal

Opt-out directives using "use no memo" should be treated as temporary. The recommended approach is: add the directive with a TODO comment, create a tracking issue, fix the underlying problem, then remove the directive.

Troubleshooting directive placement

If a directive is ignored, check that it is placed first in the function body or at the very top of the module before any imports, and verify the spelling is correct ("use memo" or "use no memo").

Module-level directive must precede imports

Module-level directives must be placed before all imports to work correctly. Ensuring the directive is at the absolute top of the file is required for proper functionality.

React Compiler directives overview

React Compiler directives are special string literals placed at the beginning of a function body or at the top of a module to control whether specific functions are compiled. They provide fine-grained control over which functions are optimized by the compiler.

use memo directive

The "use memo" directive opts a function into compilation by the React Compiler. It is placed as a string literal at the beginning of a function body. It forces compilation when using annotation mode or can override infer mode heuristics.

use no memo directive

The "use no memo" directive opts a function out of compilation by the React Compiler. It is placed as a string literal at the beginning of a function body. It is used for debugging issues or working with incompatible code.

Function-level directive placement

Function-level directives are placed at the beginning of a function body to control that specific function's compilation. Example: function OptimizedComponent() { "use memo"; return <div>This will be optimized</div>; }

Babel configuration for compilationMode

The compilationMode can be configured in babel.config.js: `module.exports = { plugins: [['babel-plugin-react-compiler', { compilationMode: 'annotation' }]] }`. Valid options are 'annotation', 'infer', or 'all'.

"use memo" directive marks functions for React Compiler optimization

The "use memo" directive marks a function for optimization by the React Compiler. When added at the beginning of a function body, it signals to the compiler to analyze and optimize that function during build time, automatically memoizing values and components to prevent unnecessary re-computations and re-renders.

"use memo" directive placement and syntax requirements

The "use memo" directive must be placed at the very beginning of a function body, before any imports or other code (though comments are allowed). It must be written with double or single quotes, not backticks. The directive must exactly match "use memo". Only the first directive in a function is processed; additional directives are ignored.

"use memo" behavior varies by compilationMode

The effect of "use memo" depends on the compilationMode setting: In annotation mode, only functions with "use memo" are optimized. In infer mode, the compiler uses heuristics but "use memo" forces optimization. In all mode, everything is optimized by default, making "use memo" redundant.

"use memo" in annotation mode example

```js // ✅ This component will be optimized function OptimizedList() { "use memo"; // ... } // ❌ This component won't be optimized function SimpleWrapper() { // ... } ``` This example demonstrates that in annotation mode, only components explicitly marked with "use memo" are optimized by the React Compiler.

"use memo" in infer mode example

```js // Automatically memoized because this is named like a Component function ComplexDashboard({ data }) { // ... } // Skipped: Is not named like a Component function simpleDisplay({ text }) { // ... } ``` In infer mode, the compiler automatically detects components by their naming patterns (PascalCase for components). Functions with lowercase names are skipped unless marked with "use memo".

"use memo" not needed in most cases

In most cases, "use memo" is not needed. It is primarily needed in annotation mode where explicit marking is required. In infer mode, the compiler automatically detects components and hooks by their naming patterns (PascalCase for components, use prefix for hooks). If a component or hook is not being compiled in infer mode, the naming convention should be fixed rather than forcing compilation with "use memo".

Verify "use memo" optimization with React DevTools

To confirm a component is being optimized by "use memo", check the compiled output in your build or use React DevTools to check for a Memo ✨ badge indicating the component has been optimized.

"use no memo" common use case: debugging compiler issues

When you suspect the compiler is causing issues, temporarily disable optimization using "use no memo" to isolate the problem. The directive should include a TODO comment explaining the reason and referencing the issue being debugged.

"use no memo" common use case: third-party library integration

When integrating with libraries that might not be compatible with the compiler, use "use no memo" to prevent optimization. This is useful when a third-party hook has side effects that the compiler might optimize incorrectly.

"use no memo" must appear before any code execution

The "use no memo" directive is ineffective if placed after code execution. For example, placing "use no memo" after a function call like getData() will not work. The directive must be the first statement in the function body.

"use no memo" is intended as temporary, not permanent

The "use no memo" directive is intended as a temporary debugging tool, not a permanent solution. When using this directive, always document why optimization is being disabled with a comment or TODO, making it clear that it should be removed after the issue is resolved.

"use no memo" directive prevents React Compiler optimization

The "use no memo" directive prevents a function from being optimized by React Compiler. When a function contains "use no memo", the React Compiler will skip it entirely during optimization. This is useful as a temporary escape hatch when debugging or when dealing with code that doesn't work correctly with the compiler.

"use no memo" placement and syntax rules

The "use no memo" directive must be at the very beginning of a function body, before any imports or other code (comments are OK). The directive must be written with double or single quotes, not backticks. The directive must exactly match "use no memo" or its alias "use no forget". This directive takes precedence over all compilation modes and other directives.

"use no memo" applies to all compilation modes

The "use no memo" directive takes precedence over all other settings. In "all" mode, the function is skipped despite the global setting. In "infer" mode, the function is skipped even if heuristics would optimize it. The compiler treats these functions as if the React Compiler wasn't enabled, leaving them exactly as written.

"use no memo" module-level vs function-level scope

The "use no memo" directive can be placed at the top of a file to affect all functions in that module, or at the function level to affect only that function. When "use no memo" appears at the function level, it overrides the module level directive.

"use no memo" example: basic function usage

function MyComponent() { "use no memo"; // Function body }

Give your agent this brain