Does React Compiler Make useMemo and useCallback Unnecessary?

​​React​React Compiler,TypeScript,useCallback,useMemo

With React Compiler, you rarely need to write useMemo and useCallback in new code. But they are not "completely unnecessary." They are still worth writing by hand in components the compiler skips, and when you want fine control over effect dependencies.

In my test environment, I transformed the same component, written in TypeScript (.tsx), two ways: without the compiler and with it. Then I counted how many times the child rendered and how many times the effect ran. I'll go through the results alongside the guidance in the official documentation.

Note

The test environment was Ubuntu 24.04 with Node.js 22.22.0. I used react / react-dom 19.3.1, babel-plugin-react-compiler 1.0.0, @babel/core 8.0.7, @babel/preset-typescript 8.0.7, typescript 7.0.2, @types/react 19.3.0, and jsdom 29.1.1. The code examples are written in .tsx. I type-checked them with tsc, transformed them with Babel, and rendered them on jsdom. I did not test with Vite or Next.js builds. For the images, I bundled the same transformed output into a single file with esbuild and ran it in Chromium via Playwright 1.56.1.

The official answer: "Let the compiler handle it by default, and write it only where needed"

The React Compiler introduction page in the official docs covers how to handle useMemo, useCallback, and React.memo. The key points are:

  • The compiler analyzes your code and memoizes automatically. In many cases, this memoization is as precise as, or more precise than, what you would write by hand.
  • You can keep using useMemo and useCallback together with the compiler as a way to decide for yourself which values get memoized, instead of leaving it to the compiler. A common example is using a memoized value as an effect dependency.
  • For new code, leave memoization to the compiler and use useMemo / useCallback only where needed.
  • For existing code, either leave the current memoization in place or test carefully before removing it (removing it can change the compilation output).

The same guidance appears in the React Compiler v1.0 announcement post.

Does a parent without useMemo stop child re-renders and effect runs?

First, I prepared a parent component with neither useMemo nor useCallback. The parent updates its own state each time the button is clicked. The child is wrapped in memo and receives an array and a function from the parent.

tsx
export function Parent({ data }: { data: number[] }) {
  const [count, setCount] = useState(0);
  const items = data.filter((x) => x % 2 === 0);                  // new array every time
  const handleSelect = (i: number) => console.log('select', i);   // new function every time
  const options = { size: items.length };                          // new object every time
  useEffect(() => { log.effectRuns++; }, [options]);
  return (
    <div>
      <button id="inc" onClick={() => setCount(count + 1)}>{count}</button>
      <Child items={items} onSelect={handleSelect} />
    </div>
  );
}

Without the compiler, the array, function, and object are recreated on every render. So even with memo, the child should render every time, and the effect should run every time. Here are the results after the initial render followed by three button clicks:

text
$ node run.mjs ./out/app.plain.mjs
./out/app.plain.mjs: button=3 childRenders=4 effectRuns=4

$ node run.mjs ./out/app.compiled.mjs
./out/app.compiled.mjs: button=3 childRenders=1 effectRuns=1

Without the compiler (plain), the child rendered 4 times and the effect ran 4 times. With the compiler (compiled), both happened only once, on the initial render. Even without writing useMemo or useCallback, I got the same result as writing them by hand.

When writing in TypeScript, the Babel config only needed @babel/preset-typescript added to the combination of the compiler plugin and @babel/preset-react. Type annotations are stripped during the transform. I also tried a version of the same component written in JavaScript (.jsx), and the counts were the same in every measurement in this article.

I also ran the same two transformed outputs in a browser, stacked one above the other. I bundled them into a single file with esbuild and, in Chromium via Playwright 1.56.1, clicked the top and bottom buttons alternately, three times each. The GIF animation below was made by capturing the screen frame by frame and stitching the frames together at 0.08-second intervals.

The band at the top of the screen shows which click it is. Any number that changed right after a click gets a pink background. At the very bottom of the screen, I added a note that both come from the same source, src/app.tsx. In the top version, without the compiler, the child render count and the effect run count go up with every click. In the bottom version, with the compiler, both stay at 1.

The parent without the compiler and the parent with the compiler are stacked top and bottom, and the cursor clicks both buttons alternately, three times each. In the top version without the compiler, the child render count and the effect run count go up to 4 with each click, and the field turns pink each time. In the bottom version with the compiler, only the number on the button goes up, and both counts stay at 1. The very bottom reads (in Japanese) "Both are the same src/app.tsx (TypeScript), transformed with Babel"
GIF animation: how the render count and effect run count change when the top and bottom buttons are clicked alternately, three times each

Note that the child component used in this test mutates a module variable to count its renders. This breaks the Rules of React, so the compiler skipped the child (it is recorded in the test log as an error at line 8). However, since the child is wrapped in memo, this does not affect the comparison.

Looking at the transformed code shows why the counts did not go up with the compiler. The compiler sets up a cache slot for each value (such as $[0]) and recreates the value only when the values it depends on change.

js

let t1;
  if ($[0] !== data) {
    t1 = data.filter(_temp);
    $[0] = data;
    $[1] = t1;
  } else {
    t1 = $[1];
  }
  const items = t1;
  const handleSelect = _temp2;

handleSelect doesn't use any values from inside the component, such as props or state, so it was moved outside the component and became a function named _temp2. The child receives the same function every time, so memo works.

What happens to useMemo you've already written?

Next, I transformed a component that already uses useMemo and useCallback.

tsx
type ListProps = { data: number[]; onPick: (i: number) => void };

export function List({ data, onPick }: ListProps) {
  const items = useMemo(() => data.filter((x) => x % 2 === 0), [data]);
  const handle = useCallback((i: number) => onPick(i), [onPick]);
  return <ul>{items.map((i) => <li key={i} onClick={() => handle(i)}>{i}</li>)}</ul>;
}

When I searched the transformed code for useMemo and useCallback, only the import line was left.

text
$ grep -n 'useMemo\|useCallback' out/existing.compiled.mjs
2:import { useMemo, useCallback } from 'react';

The useMemo and useCallback calls had been replaced with the compiler's own cache (in the form if ($[0] !== data) { ... }). In this example, the code doesn't end up memoized twice, once by hand and once by the compiler. However, according to the official docs, removing manual memoization can change the compilation output. For existing code, it's safest to test before deciding whether to delete it, as in the guidance above.

If the compiler skips a component, automatic memoization doesn't apply

The compiler assumes your code follows the Rules of React. According to the official page on debugging the compiler, when the compiler finds code that may break the rules, it skips optimizing that component. This is so it doesn't change the behavior.

So I added one line to the earlier parent that "mutates props during render." I also changed the props type so it can be mutated. This breaks the Rules of React, but the types allow the mutation, so the tsc type check passes with no errors.

tsx
type Data = number[] & { lastRendered?: number };

export function Parent({ data }: { data: Data }) {
  data.lastRendered = Date.now();   // mutate props during render (rule violation)
  // the rest is the same

The compiler log showed the following error. However, the build itself did not fail, and this component was output without being transformed.

text
CompileError line 16 | This value cannot be modified | Modifying component props or hook arguments is not allowed. Consider using a local variable instead

With this line in place, I compared the version without useMemo and the version with useMemo / useCallback written by hand. Both went through the compiler.

text
$ node run.mjs ./out/bailout.compiled.mjs
./out/bailout.compiled.mjs: button=3 childRenders=4 effectRuns=4

$ node run.mjs ./out/bailout-manual.compiled.mjs
./out/bailout-manual.compiled.mjs: button=3 childRenders=1 effectRuns=1
Warning

A component skipped by the compiler runs as code without memoization. If you delete a manual useMemo and the component is later skipped, the child re-renders and effect runs will happen on every render again.

The manual version stopped at one child render and one effect run, even though the compiler skipped it. The official guidance to "keep existing memoization, or test before removing it" pays off in cases like this.

Also, if you write "use no memo" at the top of a function, the compiler skips that function as well. In my test environment, the version with this directive had 4 child renders and 4 effect runs. The official docs describe this directive as a temporary tool for debugging.

I put the measurements for all five versions so far into one chart. In every version, the effect run count was the same as the child render count.

A horizontal bar chart comparing child render counts after three button clicks for five versions written in TypeScript. Three versions rendered 4 times: without the compiler, the version without useMemo that was skipped due to a rule violation, and the version with "use no memo". Two versions rendered once: with the compiler, and the version that was skipped but has useMemo written by hand

When writing them by hand still makes sense

Based on these results and the official docs, writing useMemo / useCallback by hand still makes sense in the following cases:

  • When you want fine control over effect dependencies so they change only when you intend (the example given in the official docs)
  • When writing a component that the compiler will skip (it breaks a rule, it has "use no memo", and so on)
  • In existing code, when you haven't yet tested the impact of removing them

Also, ordinary functions that are neither components nor hooks are outside the compiler's scope. In my test environment, such functions were output as-is without being transformed. According to the introduction page's explanation of memoizing expensive calculations, the compiler's memoization is not shared across components or hooks. For that reason, the same page says that if an expensive calculation is used in multiple components, you may want to consider implementing your own memoization outside of React.

How to check whether components are being skipped

You can't tell from the screen which components were skipped. In my tests, I received events through the Babel plugin's logger option and printed CompileSuccess and CompileError to check.

ts
import type { Logger } from 'babel-plugin-react-compiler';

const logger: Logger = {
  logEvent: (filename, event) => console.log(event.kind, 'fnName' in event ? event.fnName ?? '' : ''),
};
// Babel config: plugins: [['babel-plugin-react-compiler', { logger }]]

event is a type whose shape depends on the kind of event. In my test environment, writing event.fnName directly caused a tsc error. So the code checks that fnName exists with 'fnName' in event before reading it.

According to the v1.0 announcement post, rule violations can also be found with the recommended config of eslint-plugin-react-hooks. The post says this linter can be used even without installing the compiler. However, I did not test it with ESLint.

Point

In new code, you can leave memoization to the compiler and skip writing useMemo / useCallback. Existing memoization also acts as insurance for when the compiler skips a component. Test before deciding whether to remove it.

​Posted by 86