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 2 of 2.

"use no memo" example: module-level usage

"use no memo"; // All functions in this file will be skipped by the compiler

gating feature flag setup example

Feature flag module (src/utils/feature-flags.js): ```js export function shouldUseCompiler() { return getFeatureFlag('react-compiler-enabled'); } ``` Compiler configuration: ```js { gating: { source: './src/utils/feature-flags', importSpecifierName: 'shouldUseCompiler' } } ``` Generated output: ```js import { shouldUseCompiler } from './src/utils/feature-flags'; const Button = shouldUseCompiler() ? function Button_optimized(props) { /* compiled version */ } : function Button_original(props) { /* original version */ }; ```

gating option configuration for React Compiler

The gating option enables conditional compilation to control when optimized code is used at runtime. It accepts an object with source and importSpecifierName properties, or null. Default value is null.

gating option type signature

The gating option has type { source: string; importSpecifierName: string } | null. The source property is a module path string to import the feature flag from. The importSpecifierName property is a string naming the exported function to import.

gating function requirements and behavior

The gating function must return a boolean. The gating function is evaluated once at module load time, so once the JavaScript bundle has been parsed and evaluated, the choice of component remains static for the rest of the browser session.

gating bundle size impact

When using gating, both the compiled and original versions of code are included in the bundle, increasing bundle size compared to using the compiler without gating.

gating source path resolution

The source path in gating configuration should use module resolution paths (e.g., '@myapp/feature-flags') or absolute paths from project root (e.g., './src/utils/flags'). The path is not relative to babel.config.js.

gating feature flag must use named export

The gating function must be exported as a named export matching the importSpecifierName, not as a default export. For example, use 'export function shouldUseCompiler()' rather than 'export default function shouldUseCompiler()'.

gating import is added to every compiled file

When gating is configured, the import for the gating function is added to every file that contains compiled functions.

panicThreshold production usage

Production builds should always use panicThreshold set to 'none' to ensure the build never fails due to compiler issues, components that cannot be optimized run normally, and maximum components get optimized for stable production deployments.

panicThreshold option type

The panicThreshold option accepts one of three string values: 'none', 'critical_errors', or 'all_errors'.

panicThreshold default value

The default value for panicThreshold is 'none'.

panicThreshold 'none' option

The 'none' option (default and recommended) skips components that cannot be compiled and continues building without failing. This is the recommended setting for production builds.

panicThreshold 'critical_errors' option

The 'critical_errors' option fails the build only when the compiler encounters critical errors, allowing non-critical diagnostic issues to be skipped.

panicThreshold 'all_errors' option

The 'all_errors' option fails the build on any compiler diagnostic, including warnings and non-critical issues.

panicThreshold development usage example

During development, panicThreshold can be conditionally set based on NODE_ENV to use 'critical_errors' in development and 'none' in production, allowing developers to find and debug issues while preventing production build failures. A logger can be configured to capture CompileError events during development.

logEvent method signature

The logEvent method has the signature: logEvent(filename: string | null, event: LoggerEvent) => void. It is called for each compiler event with the filename and event details.

logger option configuration

The logger option in React Compiler configuration provides custom logging for compiler events during compilation. It accepts an object with a logEvent method or null as the default value.

logger caveats

Event structure may change between React Compiler versions. Large codebases generate many log entries, so filtering or sampling may be necessary for performance.

Basic logging example

Example showing how to log CompileSuccess and CompileError events: ```js { logger: { logEvent(filename, event) { switch (event.kind) { case 'CompileSuccess': { console.log(`✅ Compiled: ${filename}`); break; } case 'CompileError': { console.log(`❌ Skipped: ${filename}`); break; } default: {} } } } } ```

Detailed error logging example

Example showing how to extract detailed information from CompileError events: ```js { logger: { logEvent(filename, event) { if (event.kind === 'CompileError') { console.error(`\nCompilation failed: ${filename}`); console.error(`Reason: ${event.detail.reason}`); if (event.detail.description) { console.error(`Details: ${event.detail.description}`); } if (event.detail.loc) { const { line, column } = event.detail.loc.start; console.error(`Location: Line ${line}, Column ${column}`); } if (event.detail.suggestions) { console.error('Suggestions:', event.detail.suggestions); } } } } } ```

CompileError event detail structure

CompileError events contain a detail object with required property reason (string), and optional properties description (string), loc (object with start property containing line and column numbers), and suggestions (array or string).

logger configuration type

The logger option type is: { logEvent: (filename: string | null, event: LoggerEvent) => void; } | null. The default value is null.

LoggerEvent kinds

React Compiler logger supports the following event kinds: CompileSuccess (function successfully compiled), CompileError (function skipped due to errors), CompileDiagnostic (non-fatal diagnostic information), CompileSkip (function skipped for other reasons), PipelineError (unexpected compilation error), and Timing (performance timing information).

React Compiler target valid values

Valid target values are: '19' (target React 19, no additional runtime required, default); '18' (target React 18, requires react-compiler-runtime package); '17' (target React 17, requires react-compiler-runtime package). Always use string values, not numbers. Do not include patch versions.

React Compiler target option configuration

The 'target' option in react-compiler configuration specifies which React version the compiler should generate code for. It accepts string values '17', '18', or '19'. The default value is '19'.

React 19 compiler runtime handling

React 19 includes built-in compiler runtime APIs. No additional runtime package installation is needed. The compiled output imports from 'react/compiler-runtime': import { c as _c } from 'react/compiler-runtime'

React 17 and 18 compiler runtime setup

React 17 and 18 require installing the react-compiler-runtime package separately. Install with: npm install react-compiler-runtime@latest. The compiled output imports from the standalone package: import { c as _c } from 'react-compiler-runtime'

Compiler target configuration examples

Example configurations: For React 19, either omit the target option or use { target: '19' }. For React 18, use { target: '18' }. For React 17, use { target: '17' }.

React compiler runtime import difference

React 19 uses built-in runtime and imports from 'react/compiler-runtime'. React 17 and 18 use the polyfill runtime and import from 'react-compiler-runtime' (standalone package). The import path difference indicates which runtime is being used.

React compiler target must match React version

The configured target version must match the actual React major version installed in your project. Mismatches will cause runtime errors about missing compiler runtime.

React compiler runtime package placement

The react-compiler-runtime package (for React 17/18) must be installed in the project dependencies, not globally and not in devDependencies, as it is required at runtime.

React Compiler sections

React Compiler reference includes Configuration for configuration options, Directives for function-level directives to control compilation, and Compiling Libraries as a guide for shipping pre-compiled library code.

React Compiler purpose

The React Compiler is a build-time optimization tool that automatically memoizes React components and values.

React Compiler automatically generates memoization

The React Optimizing Compiler (React Forget) automatically generates the equivalent of useMemo and useCallback calls to minimize re-rendering costs while retaining React's programming model. A rewritten architecture allows analyzing and memoizing complex patterns including local mutations, and opens optimization opportunities beyond memoization hooks.

React Forget supported language subset

React Forget started with a representative subset of JavaScript including: let/const, if/else, for loops, objects, arrays, primitives, function calls, and a few other features. The supported subset is incrementally expanded. Unsupported syntax is explicitly logged with diagnostics and compilation is skipped for unsupported input.

React Forget compiler overview

React Forget is an optimizing compiler for React designed to ensure apps have the right amount of reactivity by default. While it achieves automatic memoization, it is better understood as an automatic reactivity compiler that re-renders only when state values meaningfully change, not just when object identity changes, without incurring runtime cost of deep comparisons.

React Forget production status

After significant refactors starting late 2022, React Forget has begun being used in production in limited areas at Meta. It will be open-sourced once proven in production.

React Forget compiler architecture

The core of React Forget is decoupled from Babel. The core compiler API takes old AST as input and returns new AST as output while retaining source location data. It uses a custom code representation and transformation pipeline for low-level semantic analysis. The primary public interface will be via Babel and other build system plugins.

React Compiler automatically optimizes re-renders based on React rules

React Compiler aims to automatically re-render just the right parts of the UI when state changes without compromising React's core mental model. It models both the rules of JavaScript and the rules of React, such as component idempotence and immutability of props and state. The compiler attempts to detect when code doesn't strictly follow React's rules and will either compile safely or skip compilation if unsafe.

React Compiler now powers instagram.com in production

React Compiler is no longer a research project. As of February 2024, the compiler powers instagram.com in production, and Meta is working to ship the compiler across additional surfaces and to prepare the first open source release.

Manual memoization with useMemo, useCallback, and memo is the current solution for excessive re-renders

React Compiler replaced the need for manual memoization using useMemo, useCallback, and memo APIs. Manual memoization was previously used to tune how much React re-renders on state changes, but it clutters code, is easy to get wrong, and requires extra work to maintain.

Give your agent this brain