Babel Plugin for React Compiler

1.0.0 · active · verified Sun Apr 19

The `babel-plugin-react-compiler` package, currently at version `1.0.0`, is a core component for integrating the React Compiler (codenamed "Forget") into JavaScript projects. Its primary function is to automatically memoize React components and hook calls at compile-time, aiming to eliminate unnecessary re-renders and significantly improve application performance without requiring manual `useMemo` or `useCallback` optimizations. This plugin is developed as part of the broader React ecosystem by Facebook/Meta, closely tied to the React core libraries, particularly with the release of React 19. While the plugin itself is at an initial `1.0.0` stable release, the underlying React Compiler is an actively evolving project, receiving continuous updates and refinements alongside major React versions. Its release cadence is therefore coupled with the React framework's development cycle, which often sees patch releases for bug fixes and performance improvements, with feature updates aligning with major React releases. This compiler is a key differentiator for React, promising "zero-cost" memoization for developers.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure the `babel-plugin-react-compiler` in a `babel.config.js` file and shows a basic React component structure where the compiler can automatically optimize re-renders for a `Header` and an `ExpensiveCalculation` component when only unrelated state (`count`) updates in the parent `App` component.

/* babel.config.js */
module.exports = {
  presets: ['@babel/preset-env', '@babel/preset-react'],
  plugins: [
    // The React Compiler plugin must run first in the Babel plugin pipeline.
    'babel-plugin-react-compiler',
    // ... other Babel plugins (e.g., for TypeScript, JSX transform)
  ],
};

/* src/App.js */
import { useState } from 'react';

function Header() {
  console.log('Header re-rendered');
  return <h1>React Compiler Demo</h1>;
}

export default function App() {
  const [count, setCount] = useState(0);

  // With React Compiler, Header should not re-render when count changes
  // unless its props change or it's forced to.
  return (
    <div>
      <Header />
      <p>Count: {count}</p>
      <button onClick={() => setCount(c => c + 1)}>
        Increment
      </button>
      <ExpensiveCalculation value={count} />
    </div>
  );
}

function ExpensiveCalculation({ value }) {
  // Simulate an expensive computation that the compiler might memoize
  let result = 0;
  for (let i = 0; i < 1_000_000; i++) {
    result += Math.sqrt(i) * value;
  }
  console.log('ExpensiveCalculation re-rendered with value:', value);
  return <p>Expensive Result: {result.toFixed(2)}</p>;
}

view raw JSON →