🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

React Compiler: What It Memoizes and When

React AdvancedđŸŸĸ Free Lesson

React components re-render by design, and for most screens that is the correct behavior: a render is a cheap description of what should be on screen, and re-running it after a state change is how the interface updates. The cost appears when a component re-renders children that never change, because each one re-executes its own body, re-creates objects and functions, and passes them down again. The manual answer has been memo, useMemo and useCallback in the right places, applied by hand and forgotten the moment the code changes. The compiler takes that chore off the developer and applies it consistently across the whole tree.

â„šī¸What changed

Earlier tools asked you to mark what should be cached. This one assumes everything can be cached unless your code proves otherwise, then inserts the memoization at build time so the source stays readable.

The re-render problem it actually solves

Consider a list where the parent holds the data and the child renders a row. When the parent's unrelated state changes, it creates a fresh array identity for the rows and a fresh click handler, and because memo compares props, the row sees two new values and re-renders. Multiply that by two hundred rows and a single keystroke in an unrelated input produces thousands of component executions. The React profiler shows it clearly: a wide, shallow flame graph where every entry is the same component over and over.

Developers patch this by wrapping the row in memo, the array in useMemo and the handler in useCallback. That works, but it adds syntax that obscures intent, requires dependency arrays that must be kept correct by hand, and silently stops protecting you the moment someone adds a value to the array that the dependency list does not mention. Compilation moves the same work to build time, where it can be applied to every function in the file rather than the two you remembered to annotate.

Before and after compilation

The source below is written in the straightforward style: compute the derived value inline, pass an inline handler, render the list. After compilation, the emitted code holds the sorted array and the handler stable across renders, which is exactly what the hand-optimized version did.

// Source you write
export function ProductList({ products, onSelect }) {
  const sorted = [...products].sort((a, b) => a.price - b.price);
  const cheapest = sorted[0];

  return (
    <section>
      <p>Cheapest: {cheapest ? cheapest.name : 'none'}</p>
      <ul>
        {sorted.map((product) => (
          <ProductRow
            key={product.id}
            product={product}
            onSelect={() => onSelect(product.id)}
          />
        ))}
      </ul>
    </section>
  );
}

// Shape the compiler emits for the same component
export function ProductList({ products, onSelect }) {
  let sorted, cheapest;
  if ($[0] !== products) {
    sorted = [...products].sort((a, b) => a.price - b.price);
    cheapest = sorted[0];
    $[0] = products;
  }

  let onSelectStable;
  if ($[1] !== onSelect) {
    onSelectStable = (id) => onSelect(id);
    $[1] = onSelect;
    $[2] = onSelectStable;
  }

  return (
    <section>
      <p>Cheapest: {cheapest ? cheapest.name : 'none'}</p>
      <ul>
        {sorted.map((product) => (
          <ProductRow key={product.id} product={product} onSelect={() => onSelectStable(product.id)} />
        ))}
      </ul>
    </section>
  );
}

The array of cached slots, the dollar-sign variable in the emitted code, is a memoization store keyed by the positions in the component. Each conditional block re-runs only when its input identity changes, which is the same guarantee a correct dependency array gave you, derived automatically from the actual value rather than from a list you typed.

Rules that keep components compatible

Compilation is conservative: any pattern it cannot analyze gets left alone, which is safe but wasteful. The rules are mostly about impurity, because a function that reads or writes something outside its own scope cannot be safely reordered or skipped.

javascript
// babel.config.js
module.exports = {
  presets: ['next/babel'],
  plugins: [
    ['babel-plugin-react-compiler', {
      target: '19',
      StrictMode: true,
      enablePreserveExistingMemoizationLikelyUnnecessary: true,
    }],
  ],
};
// Compatible: pure derivations and stable module-level constants
const COLUMNS = [
  { key: 'name', label: 'Name' },
  { key: 'price', label: 'Price' },
];

function normalise(items) {
  return items.filter(Boolean).map((item) => ({ ...item, label: item.label.trim() }));
}

// Needs attention: mutating during render
function BadGreeting({ user }) {
  user.displayName = user.name.toUpperCase();
  return <p>Hello {user.displayName}</p>;
}

// Needs attention: reading a value the compiler cannot trace
let analyticsQueue = [];

function trackEvent(name) {
  analyticsQueue.push({ name, at: Date.now() });
}

function AlsoBad({ open }) {
  if (open) trackEvent('panel_opened');
  return <div>{open ? 'Open' : 'Closed'}</div>;
}

Impure functions called during render, module-level mutable state read in render, and manual cache reads that the analyzer cannot follow all reduce the amount of memoization inserted. The compiler warns about these in development rather than failing the build, and the warning is worth treating as a real finding: a render that writes to module state will behave differently in concurrent rendering no matter what the compiler does.

What the compiler will and will not do

ConcernCompiler handles itYou still handle it
Derived arrays and objects in renderYes, cached by input identityChoosing which inputs belong in the derivation
Event handlers passed to childrenYes, held stable across rendersHandlers that close over values changing each render are recreated correctly
Loops and conditionalsYes, per-path cachingKeeping branches readable so the cache hit rate stays high
Effects and dependency arraysNo, unchangedCorrect cleanup and dependencies in hooks
External mutable referencesNoKeeping render reads free of side effects
Performance of very large listsPartiallyVirtualization and splitting still required
Correctness of state ownershipNoLifting or colocating state deliberately

The honest summary is that the compiler removes a class of mistakes rather than a class of bugs. It will not fix a component that re-renders because state lives too high in the tree, and it will not make an expensive computation cheap if its inputs change on every render. What it removes is the tax you were paying for forgetting: the row you did not wrap in memo, the object you rebuilt on each render, the handler you created inline in a list. Those omissions stop being a judgment call and become the default behavior of every component in the file.

Measuring the effect honestly

Enable it on one feature, record the interaction that was slow in the React profiler, and compare commit counts and component executions before and after with the same scripted steps. Screens that were already well optimized show little change, because the manual memoization was doing the work. Screens written by people in a hurry show the largest gains, which is the intended audience.

Watch the numbers that matter rather than the ones that flatter: total component executions during the interaction, the duration of the longest commit, and the interaction to next paint. If a number does not move after enabling the compiler, the bottleneck was never memoization, and the profile will show you what it was instead.

Migrating an existing codebase

Turn the linter on first, across the repository, in warning mode. It reports the render patterns the compiler cannot optimize and the impure functions it must avoid, and that list is a work queue rather than an emergency. Fix the impure functions, since they are correctness risks regardless of the compiler, and leave the rest.

Then enable the build plugin for the whole app and delete the manual memoization that is now redundant. Keep memo on components you have separately measured as hot, and keep useEffect dependency arrays exactly as they are, because the compiler does not touch them. The final state of a migration is a codebase where the optimization syntax has disappeared and the profiler proves the renders did too.

Common Mistakes

Expecting the compiler to fix re-renders caused by state living too high in the tree

Fix: Move state closer to the components that use it first, then let the compiler handle the remaining derived values.

Mutating props or writing to module state during render

Fix: Keep render pure: perform the write in an effect or in an event handler where it cannot be re-observed.

Deleting every manual memoization before measuring

Fix: Profile before and after, and keep memoization on components the profiler still names as hot.

Treating a compiler warning as noise because the build still succeeds

Fix: Treat it as a finding about impurity, because those patterns are fragile under concurrent rendering regardless.

Key Takeaways

  • The compiler inserts memoization at build time, so source stays simple while derived values and handlers stay stable across renders
  • It assumes everything is cacheable and backs off when it cannot prove purity, which is why impure render code reduces its effect
  • Effects, dependency arrays and state ownership are untouched: those remain the developer's decisions
  • The honest win is fewer component executions during an interaction, measured in the profiler rather than assumed
  • Adopt it incrementally: linter first to build a work queue, then the plugin, then delete the manual memoization that became redundant
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement