Tech Analysis · Nov 26, 2026 · 10 min read

React Compiler: Automatic Memoization, Rules of React and Next.js Patterns

Tech Analysis

Meta's React Compiler automatically removes useMemo, useCallback and React.memo by proving component purity at build time. This analysis covers the exact rules it enforces, setup steps for Next.js 15,

React Compiler: Automatic Memoization, Rules of React and Next.js Patterns

How the React Compiler Analyzes Component Purity

The React Compiler, distributed as the Babel plugin babel-plugin-react-compiler (version 0.0.0-experimental-592953e-20240523 at time of writing), performs static analysis on JSX components and hooks. It tracks mutations, side effects, and value identity across renders to prove that a component is referentially stable.

Instead of requiring developers to wrap values in useMemo, the compiler inserts its own memoization primitives (internally called c and t in the compiled output) only where needed. This eliminates the most common source of unnecessary re-renders in large React trees: unstable callback and object references passed to child components.

The analysis is flow-sensitive and inter-procedural within a single file. It understands control flow, early returns, conditional hooks, and dependency arrays. Because it runs at build time, the runtime cost is a small fixed overhead for the tracking objects it creates, typically 2-4 additional JavaScript objects per component on initial render.

Next.js 15 (canary channel as of September 2024) includes experimental support via the reactCompiler flag in next.config.js. When enabled, it applies the compiler to all files under the app directory and pages directory unless explicitly excluded.

Exact Rules the Compiler Enforces

The compiler implements a strict subset of the "Rules of React" and adds its own constraints. Violations cause compilation errors rather than runtime bugs.

  • No side effects during render: Components must not mutate props, state, or any values closed over from outer scope. Calling localStorage.setItem or console.log at the top level of a component body is forbidden.
  • Consistent hook calls: The compiler tracks every useState, useEffect, useContext and custom hook. Conditional hooks that depend on runtime values outside of hook arguments are rejected.
  • Stable identity for values passed to JSX: Any value used as a prop or child that is not a primitive or a known stable value must be proven immutable for the lifetime of the component.
  • No mutation of objects created during render: Objects and arrays created with literals or useState initializer functions cannot be mutated later in the same render or in effects that run synchronously.
  • Pure custom hooks: Custom hooks must follow the same rules as components. The compiler analyzes the entire call graph of a custom hook.

These rules are enforced by the compiler's "Forget" analysis pass (the internal codename). When a rule is violated, the error message includes the exact line and suggests a fix, such as moving a value into a useMemo or extracting a sub-component.

Common Violations and Compiler Feedback

A frequent violation occurs when developers mutate arrays returned from useState:

const [items, setItems] = useState([]);

function addItem(newItem) {
  items.push(newItem); // Compiler error: mutation of value created during render
  setItems(items);
}

The correct pattern, which the compiler accepts, uses the functional updater:

setItems(prev => [...prev, newItem]);

Another common error is non-stable event handlers passed to DOM elements or third-party components that expect stable references. The compiler will automatically wrap eligible functions with its internal memoization unless the function closes over changing values.

Setting Up the React Compiler in a Next.js 15 Project

Start with the latest canary:

npm install next@15.0.0-canary.0 react@19.0.0-rc-5f4b6c1e-20240916 react-dom@19.0.0-rc-5f4b6c1e-20240916

Then install the compiler plugin and its peer dependencies:

npm install babel-plugin-react-compiler@0.0.0-experimental-592953e-20240523

Update next.config.js:

/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    reactCompiler: true,
  },
};

module.exports = nextConfig;

For TypeScript projects, add "jsx": "react-jsx" in tsconfig.json and ensure you are using TypeScript 5.5 or newer for better inference.

To exclude specific files (useful for third-party components or legacy code), create a .react-compilerrc file at the project root:

{
  "sources": {
    "exclude": ["**/node_modules/**", "**/legacy/**", "src/components/ThirdPartyWidget.tsx"]
  }
}

Run the development server with next dev. The compiler runs during the SWC/Babel transform step. Compilation time increases by 15-40% depending on codebase size, but this is paid only at build time.

Code Migration: From Manual Memoization to Compiler-Driven Code

Consider this typical dashboard component written for React 18:

import { useState, useMemo, useCallback } from 'react';
import { Chart } from './Chart';
import { Filters } from './Filters';

export default function Dashboard({ user }) {
  const [filter, setFilter] = useState('week');
  const [dateRange, setDateRange] = useState({ start: null, end: null });

  const processedData = useMemo(() => {
    return expensiveDataTransformation(user.data, filter, dateRange);
  }, [user.data, filter, dateRange]);

  const handleFilterChange = useCallback((newFilter) => {
    setFilter(newFilter);
    trackEvent('filter_changed', { value: newFilter });
  }, []);

  const chartConfig = useMemo(() => ({
    colors: user.theme === 'dark' ? DARK_COLORS : LIGHT_COLORS,
    height: 400,
  }), [user.theme]);

  return (
    <>
      <Filters />
      <Chart data={processedData} config={chartConfig} />
    </>
  );
}

After enabling the React Compiler, the same component can be rewritten without any memoization hooks:

import { useState } from 'react';
import { Chart } from './Chart';
import { Filters } from './Filters';

export default function Dashboard({ user }) {
  const [filter, setFilter] = useState('week');
  const [dateRange, setDateRange] = useState({ start: null, end: null });

  const processedData = expensiveDataTransformation(user.data, filter, dateRange);

  const handleFilterChange = (newFilter) => {
    setFilter(newFilter);
    trackEvent('filter_changed', { value: newFilter });
  };

  const chartConfig = {
    colors: user.theme === 'dark' ? DARK_COLORS : LIGHT_COLORS,
    height: 400,
  };

  return (
    <>
      <Filters />
      <Chart data={processedData} config={chartConfig} />
    </>
  );
}

The compiler proves that handleFilterChange and chartConfig are stable because the only changing values they depend on are state and props that already cause the parent to re-render when they change. The processedData call is left as-is because the compiler cannot prove that expensiveDataTransformation is pure; you must either mark it with the "use no memo" comment or move the expensive work into a web worker or server component.

Advanced Compiler Directives and Escape Hatches

When the compiler cannot prove safety, it provides two escape hatches. The first is the useMemo hook itself, which the compiler respects and will not attempt to optimize further. The second is the special comment:

// use no memo
const unstableValue = calculateSomething risky(props);

A more powerful directive is use forget placed at the top of a component or hook to force the compiler to treat it as fully memoized, requiring the developer to guarantee purity manually.

For libraries that mutate props (many older chart libraries do this), wrap them in a component marked with use no memo or move the instance into a useRef and update it in an effect.

Interaction with Server Components and Streaming

In Next.js 15 with React 19, the compiler works on both client and server components, but its effect is different. Server Components run only once per request, so memoization is less relevant. However, the compiler still validates that Server Components follow the Rules of React, catching accidental mutations that would break streaming or React Server Components (RSC) payload serialization.

When a Client Component is passed a Server Component as a child, the compiler ensures the Client Component does not attempt to mutate the server-rendered tree. This combination reduces the number of "client boundary" components that previously required heavy useMemo usage to prevent rerenders.

Streaming boundaries created with <Suspense> benefit because the compiler reduces the number of reconciliation paths that cause fallback re-rendering when state updates occur higher in the tree.

Performance Trade-offs and When the Compiler Helps Most

The compiler shines in component trees with 5+ levels of nesting and frequent state updates that previously caused widespread re-renders due to unstable callbacks. Typical candidates are dashboards, design tools, IDE-like interfaces, and complex forms.

Trade-offs include:

  • Build time: The analysis adds 20-60ms per file on a modern MacBook. Large codebases may see 15-25% longer build times.
  • Bundle size: The inserted tracking code adds roughly 800 bytes (gzipped) per compiled component that uses non-primitive values. This is usually offset by removal of useMemo and useCallback calls.
  • Debugging: Compiled output uses internal symbols ($ prefix and temporary variables) that can make React DevTools and source maps harder to read. Use the reactCompiler sourcemap option during development.
  • Third-party compatibility: Any library that violates the Rules of React (for example, by mutating props) must be isolated behind a memo boundary or excluded from compilation.

The compiler does not replace profiling. Use React Profiler and Lighthouse to identify whether excessive renders are actually coming from the component tree or from other sources such as context providers or global state libraries.

Integration with TypeScript, ESLint and Testing

The React Compiler works well with TypeScript 5.5+ because the type system helps prove non-mutability of certain values. However, any types disable some analysis paths.

Meta provides an ESLint plugin (eslint-plugin-react-compiler) that mirrors the compiler rules for editor feedback. Add it to your .eslintrc:

{
  "plugins": ["react-compiler"],
  "rules": {
    "react-compiler/react-compiler": "error"
  }
}

Tests written with React Testing Library continue to work unchanged. Because the compiler only affects production and development builds with the flag enabled, your test environment (usually using @testing-library/react with jsdom) does not run the compiler unless explicitly configured.

For Jest or Vitest snapshot tests, the compiled output differs, so it is recommended to snapshot at the JSX level or disable the compiler in test environments using the .react-compilerrc exclusion for **/__tests__/**.

Real-World Migration Strategy for Existing Codebases

Large codebases should migrate incrementally. Start by enabling the compiler on a single directory using the sources.include option in .react-compilerrc:

{
  "sources": {
    "include": ["src/components/dashboard/**"]
  }
}

Fix errors one component at a time. The most common fixes are:

  1. Replacing array mutations with immutable updates or libraries like Immer (the compiler understands Immer's produce when used correctly).
  2. Extracting components that perform side effects during render into custom hooks marked use no memo.
  3. Moving expensive calculations into separate web workers or to the server via Route Handlers or Server Actions.

After migration of a feature, measure before and after using the React Profiler's "Highlight updates" feature and production performance monitoring. Teams that have completed this process on mid-sized applications (approximately 400 components) report significantly fewer useMemo related bugs and easier onboarding for new developers who no longer need to understand dependency array pitfalls.

Limitations and Future Evolution

The current experimental compiler cannot analyze across file boundaries. A component calling a function imported from another file receives conservative treatment unless that function is marked with a special comment or is a known pure utility.

Integration with certain state management solutions requires care. Zustand and Jotai work well because they return stable references by design. Redux, especially with older connect patterns, often triggers conservative memoization because the store subscription can return new objects on every state update.

React 19 itself adds the use hook for promises and resources. The compiler understands use and treats it as a stable hook call. This combination enables powerful patterns where data fetching logic can live inside components without manual memoization of the resulting values.

Future versions are expected to improve cross-module analysis and add support for more libraries through a "trusted dependencies" configuration file. The long-term goal stated by the React team is to make manual memoization the exception rather than the default for new code.

Checklist for Adopting the React Compiler

  • Upgrade to React 19 RC and Next.js 15 canary
  • Install and configure babel-plugin-react-compiler
  • Enable experimental.reactCompiler in next.config.js
  • Add the ESLint plugin for immediate feedback
  • Exclude known-violating third-party components
  • Migrate one feature at a time, fixing compiler errors
  • Update tests that assert on rendered HTML if they are sensitive to extra wrapper elements (rare)
  • Measure render counts before and after using React DevTools Profiler
  • Document components that intentionally use use no memo

Following this checklist minimizes risk when introducing the compiler to production applications. The reduction in cognitive load around memoization is substantial, letting developers focus on business logic instead of render optimization trivia.

The React Compiler represents a significant shift in how we write React code. By moving optimization decisions from runtime to build time and enforcing stricter rules, it produces more predictable and often faster user interfaces with less manual scaffolding. For teams building complex interactive applications with Next.js, the investment in migration pays off through cleaner code and fewer performance regressions.

Keep reading

Related Research