Skip to main content

React Compiler 1.0: Automatic Memoization and When You Still Need useMemo

A practical guide to React Compiler 1.0. Learn how automatic memoization works, how to set it up in Vite and Next.js 16, which Rules of React it depends on, how to adopt it incrementally, and when manual useMemo and useCallback still matter.

Table of Contents


Introduction

For years, keeping React apps fast meant sprinkling React.memo, useMemo, and useCallback across your codebase. It worked, but it came with real costs: noisy code, dependency arrays that drifted out of sync, and endless code review debates about whether a particular useCallback was “worth it.”

React Compiler changes that. Released as stable 1.0 in October 2025, it’s a build-time tool that analyzes your components and hooks and inserts memoization automatically. You write plain React, and the compiler figures out which values, callbacks, and JSX can be cached between renders. Meta has run it in production on apps like the Meta Quest Store, and frameworks like Next.js 16 and Expo now ship first-class support for it.

But “automatic” doesn’t mean “magic.” The compiler only optimizes code that follows the Rules of React, it skips components it can’t reason about, and there are still a handful of cases where manual memoization is the right call.

This guide covers how React Compiler works under the hood, how to set it up in Vite, Next.js, and plain Babel, how to adopt it safely in an existing codebase, and when you should still reach for useMemo and useCallback. If you need a refresher on manual memoization first, see our React performance optimization guide.


What React Compiler Actually Does

React re-renders a component whenever its state changes or its parent re-renders. By default, every render recreates every object, array, function, and JSX element inside that component. Most of the time that’s fine, but when those new references flow into child components or effect dependencies, they trigger extra work.

Manual memoization fixes this by caching values between renders:

function ProductList({ products, filter, onSelect }: ProductListProps) {
// Cache the filtered list until products or filter change
const visibleProducts = useMemo(
() => products.filter((p) => p.category === filter),
[products, filter]
);
// Keep a stable function reference for the memoized child
const handleSelect = useCallback(
(id: string) => onSelect(id),
[onSelect]
);
return <MemoizedGrid items={visibleProducts} onSelect={handleSelect} />;
}
const MemoizedGrid = React.memo(Grid);

React Compiler does the same thing at build time, without the hooks:

// ✅ With React Compiler: write plain React
function ProductList({ products, filter, onSelect }: ProductListProps) {
const visibleProducts = products.filter((p) => p.category === filter);
const handleSelect = (id: string) => onSelect(id);
return <Grid items={visibleProducts} onSelect={handleSelect} />;
}

The compiled output caches visibleProducts, handleSelect, and even the <Grid /> element itself. If products, filter, and onSelect haven’t changed, React receives the exact same element as last time and skips re-rendering Grid entirely, which is the same effect React.memo would have had.

Key Differences from Manual Memoization

AspectManual (useMemo / useCallback)React Compiler
Dependency trackingYou write dependency arrays by handInferred from data flow
GranularityPer hook callPer value, including individual JSX nodes
Conditional codeHooks can’t be called conditionallyCan memoize after early returns
JSX memoizationRequires React.memo on childrenElements are cached in the parent
Correctness riskStale closures from missing depsBails out if it can’t prove safety
Code noiseHighNone in source code

That “conditional code” row is worth highlighting. Because hooks must be called unconditionally, you can’t put a useMemo after an early return. The compiler has no such restriction:

function OrderSummary({ order }: { order: Order | null }) {
if (!order) {
return <EmptyState />;
}
// The compiler memoizes this even though it comes after an early return.
// A useMemo here would violate the Rules of Hooks.
const total = order.items.reduce((sum, item) => sum + item.price * item.qty, 0);
return <Summary order={order} total={total} />;
}

How Compiled Code Looks

Understanding the output helps you trust the compiler and debug it when something seems off. Take this simple component:

function Greeting({ name }: { name: string }) {
const message = `Hello, ${name}!`;
return <h1 className="greeting">{message}</h1>;
}

The compiler transforms it into something roughly like this (simplified for readability):

import { c as _c } from "react/compiler-runtime";
function Greeting({ name }) {
const $ = _c(2); // Allocate a cache with 2 slots for this component
let t0;
if ($[0] !== name) {
// Input changed: recompute and store the result
const message = `Hello, ${name}!`;
t0 = <h1 className="greeting">{message}</h1>;
$[0] = name;
$[1] = t0;
} else {
// Input unchanged: reuse the cached element
t0 = $[1];
}
return t0;
}

A few things to notice:

  • _c(n) allocates a per-component-instance cache array. It’s backed by a hook internally, so it lives as long as the component is mounted.
  • Reactive inputs (props, state, context values) are compared with !==, the same strict equality React uses everywhere else.
  • Values that never change (like a static JSX subtree) are computed once and stored using a sentinel check, so they’re never recreated.

You can paste any component into the React Compiler Playground to see its exact compiled output. It’s the fastest way to answer “did the compiler optimize this, and how?”

💡 Tip: If the playground shows your component unchanged, the compiler bailed out. The playground output usually includes a diagnostic explaining why.


Setting Up React Compiler

React Compiler ships as a Babel plugin, babel-plugin-react-compiler. Most toolchains wrap it so you rarely configure Babel directly.

Prerequisites

  • React 19 (recommended), or React 17/18 with an extra runtime package
  • A build tool that can run Babel on your app code (Vite, Next.js, Expo, Webpack, Rsbuild, etc.)
  • eslint-plugin-react-hooks v6 or later for compiler-aware lint rules

Install the plugin as a dev dependency:

Terminal window
npm install -D babel-plugin-react-compiler@latest

⚠️ Important: The compiler must run first in your Babel plugin pipeline. It needs to see your original source code before other transforms (like JSX or TypeScript stripping in some setups) rewrite it.


Vite

With @vitejs/plugin-react, pass the compiler through the babel option:

vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [
react({
babel: {
plugins: ["babel-plugin-react-compiler"],
},
}),
],
});

If you use @vitejs/plugin-react-swc instead, note that it doesn’t run Babel, so you’ll need to switch to @vitejs/plugin-react or use a separate Babel step for the compiler. For most apps, switching is a one-line change.

To pass compiler options, use the tuple form:

react({
babel: {
plugins: [
[
"babel-plugin-react-compiler",
{
// Options go here, e.g. target or compilationMode
},
],
],
},
});

Next.js 16

Next.js 16 promoted compiler support out of experimental. Enable it with a single flag:

next.config.ts
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
reactCompiler: true,
};
export default nextConfig;

You still need babel-plugin-react-compiler installed. Next.js uses SWC for everything else, and it’s smart about it: it only runs the Babel-based compiler on files that contain JSX or hooks, so the build-time cost stays small.

To pass options, use an object instead of true:

const nextConfig: NextConfig = {
reactCompiler: {
compilationMode: "annotation", // Only compile opted-in components
},
};

💡 Tip: Server Components benefit less from the compiler since they render once per request and don’t re-render. The gains show up in your Client Components, which is where interactivity and re-renders happen. For a deeper look at that split, see our Server Components vs Client Components guide.


Babel and Other Toolchains

If you control Babel directly, add the plugin first in the list:

babel.config.js
module.exports = {
plugins: [
"babel-plugin-react-compiler", // Must run first
// ...other plugins
],
presets: [
"@babel/preset-env",
"@babel/preset-react",
"@babel/preset-typescript",
],
};

Other ecosystems have their own integration:

ToolchainHow to enable
ExpoEnabled by default in new apps since SDK 54
WebpackAdd the plugin to babel-loader’s config
RsbuildUse @rsbuild/plugin-babel with the compiler plugin
React RouterConfigure through the Vite plugin, same as plain Vite

React 17 and 18 Support

The compiled output imports a tiny runtime from react/compiler-runtime, which only exists in React 19. For older versions, install the standalone runtime and tell the compiler your target:

Terminal window
npm install react-compiler-runtime@latest
vite.config.ts
react({
babel: {
plugins: [["babel-plugin-react-compiler", { target: "18" }]], // or "17"
},
});

This makes the compiler a viable stepping stone: you can get automatic memoization before committing to a full React 19 upgrade. When you’re ready for that, our React 19 migration guide walks through the process.


The Rules of React the Compiler Relies On

The compiler doesn’t execute your code. It reasons about it statically, and that reasoning is only valid if your components follow the Rules of React. When the compiler detects a violation, it skips that component or hook and leaves it unoptimized. It doesn’t fail the build, and it doesn’t try to “fix” your code.

These are the rules that matter most:

1. Components and Hooks Must Be Pure

Rendering must not have side effects, and the same inputs must produce the same output.

// ❌ Impure: reads a value that changes between renders
function Timestamp() {
const now = Date.now(); // Different every render
return <span>{now}</span>;
}
// ✅ Pure: the impure read happens in state initialization or an effect
function Timestamp() {
const [now] = useState(() => Date.now());
return <span>{now}</span>;
}

2. Props and State Are Immutable

Mutating props, state, or values derived from them breaks the compiler’s assumption that “same reference means same value.”

// ❌ Mutates a prop: the cached result would go stale
function SortedList({ items }: { items: Item[] }) {
items.sort((a, b) => a.name.localeCompare(b.name));
return <List items={items} />;
}
// ✅ Creates a new array instead
function SortedList({ items }: { items: Item[] }) {
const sorted = items.toSorted((a, b) => a.name.localeCompare(b.name));
return <List items={sorted} />;
}

Local mutation is fine. Building up a new array with push inside the component is safe, because nobody else holds a reference to it yet.

3. Don’t Read or Write Refs During Render

Refs are an escape hatch for values that don’t participate in rendering. Reading ref.current during render makes the output depend on something the compiler can’t track.

// ❌ Reads a ref during render
function Counter() {
const renderCount = useRef(0);
renderCount.current++;
return <p>Rendered {renderCount.current} times</p>;
}
// ✅ Refs read in event handlers and effects are fine
function SearchInput() {
const inputRef = useRef<HTMLInputElement>(null);
const focus = () => inputRef.current?.focus();
return (
<>
<input ref={inputRef} />
<button onClick={focus}>Focus</button>
</>
);
}

4. Don’t Define Components Inside Components

A component defined inside another gets a new identity every render, which resets its state and defeats memoization.

// ❌ Row is a new component type on every render
function Table({ rows }: { rows: RowData[] }) {
const Row = ({ data }: { data: RowData }) => <tr>{/* ... */}</tr>;
return <tbody>{rows.map((r) => <Row key={r.id} data={r} />)}</tbody>;
}
// ✅ Define it at module level
const Row = ({ data }: { data: RowData }) => <tr>{/* ... */}</tr>;
function Table({ rows }: { rows: RowData[] }) {
return <tbody>{rows.map((r) => <Row key={r.id} data={r} />)}</tbody>;
}

5. Follow the Rules of Hooks

Hooks must be called unconditionally at the top level, and only from components or other hooks. Hooks are also expected to treat their arguments and return values as immutable.

These rules aren’t new. They’ve been in the React docs for years. What’s new is that breaking them now has a visible cost: the compiler silently opts that code out of optimization.


Linting with eslint-plugin-react-hooks

The best way to find violations is the linter. As of eslint-plugin-react-hooks v6, the compiler’s diagnostics are built right into the plugin you’re probably already using. The standalone eslint-plugin-react-compiler package is deprecated.

Terminal window
npm install -D eslint-plugin-react-hooks@latest
eslint.config.js
import reactHooks from "eslint-plugin-react-hooks";
import { defineConfig } from "eslint/config";
export default defineConfig([reactHooks.configs.flat.recommended]);

The recommended preset includes the classic rules-of-hooks and exhaustive-deps rules plus compiler-powered rules such as:

RuleWhat it catches
react-hooks/purityImpure calls like Date.now() or Math.random() in render
react-hooks/immutabilityMutating props, state, or hook return values
react-hooks/refsReading or writing ref.current during render
react-hooks/set-state-in-renderCalling setState unconditionally during render
react-hooks/set-state-in-effectSynchronous setState in effects that causes extra renders
react-hooks/static-componentsComponents defined inside other components
react-hooks/incompatible-libraryLibraries whose APIs can’t be safely memoized
react-hooks/preserve-manual-memoizationManual memoization the compiler can’t preserve

💡 Tip: Turn on the lint rules before you enable the compiler. Every warning you fix is a component that will be optimized on day one, and you’ll catch real bugs along the way. These rules are useful even if you never ship the compiler.


Incremental Adoption

Turning the compiler on for a large, older codebase all at once is usually fine. The compiler is conservative and skips what it doesn’t understand. Still, “usually fine” isn’t good enough for production, so there are several ways to roll it out gradually.

Option 1: Limit It to a Directory

With Babel’s overrides, you can compile only part of your app:

babel.config.js
module.exports = {
plugins: [
// ...other plugins, no compiler here
],
overrides: [
{
test: "./src/features/checkout/**/*.{js,jsx,ts,tsx}",
plugins: ["babel-plugin-react-compiler"],
},
],
};

Start with a well-tested, self-contained feature, verify it in production, then widen the glob.

Option 2: Opt In with “use memo”

Annotation mode compiles nothing by default. Components and hooks opt in with a directive:

// Compiler config
{
compilationMode: "annotation";
}
function Dashboard({ widgets }: DashboardProps) {
"use memo"; // Only this function gets compiled
const visible = widgets.filter((w) => w.enabled);
return <WidgetGrid widgets={visible} />;
}

This works well for teams that want to target known hot spots first.

Option 3: Opt Out with “use no memo”

If the compiler is on everywhere and one component misbehaves, opt it out while you investigate:

function LegacyChart({ data }: ChartProps) {
"use no memo"; // Temporary escape hatch: skip compilation
// ...code that mutates a third-party chart instance during render
}

⚠️ Treat "use no memo" as a TODO, not a solution. If a component breaks under the compiler, it almost always means it breaks a Rule of React, and that same code is likely fragile under concurrent rendering and Strict Mode too. Add a comment linking to an issue and fix the root cause.

Option 4: Gate It Behind a Feature Flag

For the most cautious rollouts, the compiler supports a gating option. It emits both the original and compiled versions of each function and picks one at runtime based on a function you provide. This lets you A/B test the compiler against real traffic before committing.

// Compiler config
{
gating: {
source: "@/lib/feature-flags", // Module that exports the check
importSpecifierName: "isReactCompilerEnabled",
},
}

Gating increases bundle size because both versions are shipped, so use it for the rollout period only.


When You Still Need useMemo and useCallback

The official guidance is clear: for new code, rely on the compiler and only reach for manual memoization when you need precise control. For existing code, leave your current useMemo and useCallback calls in place. The compiler works alongside them, and removing them can subtly change behavior.

Here’s where manual memoization still earns its place.

1. Stable Effect Dependencies with Semantic Meaning

When a value is an effect dependency, its identity determines when the effect runs. That’s a correctness concern, not just performance. The compiler usually produces stable references, but making the intent explicit protects you if the compiler skips the component someday.

function ChatRoom({ roomId, serverUrl }: ChatRoomProps) {
// Explicit: the connection options change only when these two values change.
// If this object changed every render, we'd reconnect on every keystroke.
const options = useMemo(() => ({ roomId, serverUrl }), [roomId, serverUrl]);
useEffect(() => {
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [options]);
return <Messages roomId={roomId} />;
}

Better still, pass primitives as dependencies when you can ([roomId, serverUrl]) and build the object inside the effect. Then you don’t need memoization at all.

2. Values Passed to Code Outside React

Third-party libraries that compare references (charting libraries, map SDKs, editor instances, and similar) care about identity in ways the compiler can’t see. If an uncompiled library re-initializes whenever its config object changes, useMemo documents that requirement right where it matters.

function SalesChart({ data, currency }: SalesChartProps) {
// The chart library re-creates its canvas when `config` changes identity
const config = useMemo(
() => ({
type: "line",
data,
options: { scales: { y: { ticks: { callback: (v: number) => formatMoney(v, currency) } } } },
}),
[data, currency]
);
return <ThirdPartyChart config={config} />;
}

3. Custom Hooks Published as Libraries

If you publish hooks to npm, you can’t assume your consumers run the compiler. You can either compile the library yourself before publishing (the compiler supports this) or keep manual memoization so your hooks return stable values for everyone.

4. Components the Compiler Skips

If a component opts out with "use no memo", violates a rule, or lives in code the compiler doesn’t process, it doesn’t get any automatic memoization. Manual memoization is still the only tool there.

Should You Delete Existing useMemo Calls?

Not in bulk. The preserve-manual-memoization lint rule exists because the compiler tries to keep your manual memoization guarantees. Removing a useMemo can change when an effect fires, even if the compiler would have memoized the value too. Remove them opportunistically: when you’re already editing a component, it’s well tested, and the memoized value isn’t an effect dependency.

SituationRecommendation
New component, ordinary derived values✅ Plain code, let the compiler handle it
New component, value is an effect dependency⚠️ Prefer primitive deps; memoize if not possible
Existing useMemo / useCallback✅ Leave in place
Value passed to a reference-sensitive library✅ Keep or add useMemo
Published hook library✅ Pre-compile or memoize manually
React.memo on a child of compiled parents🧹 Usually redundant, safe to remove later

What the Compiler Doesn’t Fix

Automatic memoization is a big improvement, but it’s not a performance silver bullet. These problems still need your attention:

Expensive Work When Inputs Actually Change

Memoization skips work when inputs are the same. If you filter 50,000 rows and the filter text changes on every keystroke, the filter still runs on every keystroke. For that, reach for useDeferredValue or useTransition (see our concurrent features guide), debounce the input, or move the work to the server or a Web Worker.

Rendering Too Many DOM Nodes

The compiler can skip re-rendering a 10,000-row table, but the first render still creates 10,000 rows. Virtualization is still the answer for large lists.

Bundle Size and Loading

The compiler optimizes re-renders, not downloads. Code splitting, lazy loading, and trimming dependencies still matter for Core Web Vitals. Compiled output is also slightly larger than the source because of the cache logic.

Context Changes

When a context value changes, every consumer re-renders. The compiler makes those re-renders cheaper by caching unchanged subtrees, but it doesn’t stop them. Splitting large contexts or using a selector-based state library is still worthwhile. For options, see our state management comparison.

Caching Across Component Instances

The compiler’s cache is per component instance. Two <ProductCard /> components rendering the same product each compute their values separately. For shared data, use a data-fetching cache like TanStack Query or a module-level cache.


Measuring the Impact

Don’t take the compiler’s impact on faith. Measure it.

React DevTools Badges

React DevTools shows a “Memo ✨” badge next to components the compiler has optimized. It’s the quickest way to confirm the compiler is running and to spot important components it skipped.

Profiling Before and After

  1. Record a typical interaction in the React DevTools Profiler with the compiler disabled
  2. Note the number of commits, which components rendered, and their render durations
  3. Enable the compiler, rebuild, and record the same interaction
  4. Compare: you should see fewer components rendering per commit and shorter commit times

Turn on “Highlight updates when components render” in DevTools settings for a quick visual check. After enabling the compiler, the flashing across unrelated parts of the tree should drop noticeably.

Real-User Metrics

Lab profiling tells you what changed, and field data tells you whether users noticed. Track Interaction to Next Paint (INP) before and after rollout, since it’s the Core Web Vital most directly affected by render performance. Our Core Web Vitals guide covers how to collect it.

What to Expect

Results vary widely by codebase. Apps that were already carefully memoized by hand often see modest gains, while apps that never invested in memoization can see large improvements in interaction latency. Meta reported that the Quest Store saw initial loads up to 12% faster and some interactions more than twice as fast. Your mileage will depend on how much unnecessary re-rendering your app was doing.


Common Pitfalls

❌ Assuming Everything Is Compiled

The compiler skips code silently. A single impure line can opt an entire component out. Check the DevTools badges for your most important components, and keep the lint rules on so violations show up in your editor and CI.

❌ Using an Incompatible Library Without Knowing It

Some libraries return functions or objects whose results change without their identity changing, which breaks memoization assumptions. A common example is form libraries’ watch()-style APIs or table libraries that return a mutable instance. The incompatible-library lint rule flags known cases. When you hit one, isolate that usage in a small component that opts out, rather than opting out a large parent.

// ✅ Keep the incompatible API in a tiny, isolated component
function WatchedTotal({ control }: { control: Control<FormValues> }) {
"use no memo";
const total = useWatchedTotal(control); // Library hook that isn't compiler-safe
return <TotalDisplay value={total} />;
}

❌ Relying on Memoization for Correctness

If your app only works because a value is memoized (for example, an effect that loops infinitely without it), the code is fragile. The compiler may memoize at different boundaries than you expect. Fix the underlying logic: use primitive dependencies, move object creation into the effect, or use useEffectEvent for callbacks that shouldn’t re-trigger effects.

❌ Mutating Data Fetched from a Cache

Mutating objects returned from a data-fetching library (adding a computed field to a query result, for example) breaks the immutability rule and can cause stale UI under the compiler. Derive new objects instead.

// ❌ Mutates cached data
const { data: user } = useQuery(userQuery);
user.fullName = `${user.first} ${user.last}`;
// ✅ Derive a new value
const { data: user } = useQuery(userQuery);
const fullName = `${user.first} ${user.last}`;

❌ Forgetting the Compiler Must Run First

If your Babel config runs other plugins before the compiler, it may see transformed code it can’t analyze, and quietly skip it. Always list babel-plugin-react-compiler first.


Migration Checklist

Use this checklist to roll React Compiler out in an existing app:

  1. Upgrade the linter: Install eslint-plugin-react-hooks@latest and enable the recommended flat config
  2. Fix violations: Work through purity, immutability, and ref-in-render warnings, starting with your most important components
  3. Check your test coverage: Make sure your critical user flows have end-to-end tests. See our Playwright vs Cypress comparison if you need to set them up
  4. Profile a baseline: Record key interactions in React DevTools and note your current INP
  5. Install the compiler: Add babel-plugin-react-compiler@latest (plus react-compiler-runtime on React 17/18)
  6. Enable it gradually: Start with one directory via overrides or with compilationMode: "annotation"
  7. Run the full test suite, including in Strict Mode: Strict Mode’s double rendering surfaces the same impurity bugs the compiler is sensitive to
  8. Verify with DevTools: Confirm “Memo ✨” badges on your important components
  9. Ship and monitor: Watch error rates and INP, then widen the rollout
  10. Clean up over time: Remove redundant React.memo and useCallback wrappers opportunistically, never in bulk

Conclusion

React Compiler 1.0 is the biggest change to how we write performant React since hooks. It removes most of the memoization boilerplate that cluttered our components, and it does the job more precisely than most of us did by hand, all without changing how React works at runtime.

Key Takeaways:

  • The compiler memoizes automatically at build time: values, callbacks, and JSX elements, with dependencies inferred from your code
  • Setup is a few lines in Vite, Next.js 16 (reactCompiler: true), Expo, or plain Babel, and it works with React 17 and 18 via react-compiler-runtime
  • It depends on the Rules of React. Code that breaks them is skipped silently, so turn on the eslint-plugin-react-hooks rules first
  • Adopt it incrementally with directory overrides, "use memo" annotation mode, or feature-flag gating
  • Keep existing useMemo and useCallback, and still use them for effect dependencies, reference-sensitive libraries, and published hooks
  • It doesn’t replace virtualization, code splitting, deferred rendering, or good state architecture

The best part is that preparing for the compiler makes your code better even without it. Pure components, immutable data, and correct effects are easier to test, safer under concurrent rendering, and easier to reason about. For a broader look at React mistakes the compiler won’t catch, see our guide to common React pitfalls.

Next Steps:

  1. Paste a few of your components into the React Compiler Playground and read the output
  2. Enable the latest eslint-plugin-react-hooks rules and see how many violations you have
  3. Turn the compiler on for one feature directory and profile the difference
  4. Roll it out across the app once you’re confident

Happy compiling! ⚡