日本語

React 19: Returning a Cleanup Function from a ref Callback

​​React​ref,TypeScript,useCallback,useImperativeHandle

This article was translated from the Japanese original with AI. 日本語の原文を読む

React 19 lets a callback passed to ref return a function. React calls the returned function when the element is removed from the screen. This means you can write the cleanup right next to the code that sets things up in the ref.

In my test environment, I ran the same TypeScript components on React 19 and React 18, and recorded when the ref callback and the cleanup function were called. This article summarizes those results and the rules in the official documentation.

Note

The test environment was Ubuntu 24.04 and Node.js 22.22.0. For React 19, I used react / react-dom 19.3.1, @types/react 19.3.0, and typescript 7.0.2. For the React 18 comparison, I used react / react-dom 18.3.1. Both were transpiled with esbuild 0.28.2 and rendered on jsdom 29.1.1. The GIF was recorded with Playwright 1.56.1 driving Chromium 141.

How to return a cleanup function

According to the React 19 announcement, a function returned from a ref callback is called when the component is removed. For the test, I prepared the following WithCleanup. log is a helper I wrote for the test to record the order of calls.

tsx
import { log, name } from './log';

// ref callback that returns a cleanup function (a new function on every render)
export function WithCleanup({ label }: { label: string }) {
  return (
    <div
      ref={(node) => {
        log(`ref ${name(node)} (${label})`);
        return () => {
          log(`cleanup (${label})`);
        };
      }}
    >
      {label}
    </div>
  );
}

I rendered this component, re-rendered it with changed props, and then removed it. Here is the React 19 log:

text
react 19.3.1

[A. 後片付けの関数を返す(インラインの関数)]
  1. 描画
    ref <div> (one)
  2. props を変えて再描画
    cleanup (one)
    ref <div> (two)
  3. 削除
    cleanup (two)

When it rendered, the callback received the <div>. When it was removed, the returned function was called. The callback was never called with null.

Without a returned function, the callback still gets null

I also tested the pre-React 19 style, where nothing is returned. WithoutCleanup only records the value it receives and returns nothing.

text
[B. 何も返さない(インラインの関数)]
  1. 描画
    ref <div> (one)
  2. props を変えて再描画
    ref null (one)
    ref <div> (two)
  3. 削除
    ref null (two)

Even in React 19, the callback was called with null when the element was removed. The ref callback reference says this behavior exists for compatibility with the old style and will be removed in a future version. If your code needs cleanup, it is safer to switch to the style that returns a function.

In React 18, the returned function is not used

When I ran the same WithCleanup on React 18, the results were different.

text
react 18.3.1

[A. 後片付けの関数を返す(インラインの関数)]
  1. 描画
    ref <div> (one)
    console.error: Warning: Unexpected return value from a callback ref in div. A callback ref should not return a function.
  2. props を変えて再描画
    ref null (one)
    ref <div> (two)
    console.error: Warning: Unexpected return value from a callback ref in div. A callback ref should not return a function. (2回)
  3. 削除
    ref null (two)
    console.error: Warning: Unexpected return value from a callback ref in div. A callback ref should not return a function.

On React 18, the returned function was never called. When the element was removed, the callback was called with null. Each time a function was returned, React also printed the warning "A callback ref should not return a function." The marker at the end of the second warning line (in Japanese, meaning "2 times") is not part of React's output. My test script appended it when the same warning appeared twice in a row and was collapsed into one line.

Warning

If you have code that must also run on React 18 and you rely only on the returned cleanup function, cleanup never happens on React 18. For React 18, you need to clean up when the callback receives null.

Re-renders call it again because the function is new each time

In the first log, a re-render with changed props produced cleanup (one) followed by ref <div> (two). According to the reference, when React receives a different function for ref than before, it calls the previous function's cleanup, and then calls the new function with the DOM node. Writing ref={(node) => { ... }} creates a new function on every render, so this swap happens on every re-render.

If you don't want to redo the cleanup and setup on every re-render, pass the same function each time with useCallback.

tsx
import { useCallback } from 'react';
import { log, name } from './log';

// ref callback that passes the same function each time via useCallback
export function StableCallback({ label }: { label: string }) {
  const ref = useCallback((node: HTMLDivElement | null) => {
    log(`ref ${name(node)}`);
    return () => {
      log('cleanup');
    };
  }, []);
  return <div ref={ref}>{label}</div>;
}
text
[C. useCallback で同じ関数を渡す]
  1. 描画
    ref <div>
  2. props を変えて再描画
  3. 削除
    cleanup

On React 19, nothing was called during the re-render. The callback and the cleanup were called only on mount and unmount.

In Strict Mode, setup and cleanup each run one extra time on mount

The reference says that in Strict Mode, only during development, React runs setup and cleanup one extra time before the first real setup. The purpose is to check that the cleanup correctly undoes what the setup did. I rendered WithCleanup inside <StrictMode>, and that is what happened.

text
[D. StrictMode の中で A を描画]
  1. 描画
    ref <div> (one)
    cleanup (one)
    ref <div> (one)
  2. 削除
    cleanup (one)

I tried the same thing on React 18, and there was no extra call. (I omitted the warning lines.)

text
[D. StrictMode の中で A を描画]
  1. 描画
    ref <div> (one)
  2. 削除
    ref null (one)

Managing per-item DOM nodes of a list with a Map

Cleanup functions are also useful when you need to keep refs for an unknown number of elements together. Following the official Learn page example for managing a list of refs with a ref callback, I wrote a CatList that stores each <li> in a Map and removes it when it unmounts. probe is a container I used in the test to inspect the Map from outside.

tsx
import { useRef } from 'react';
import { probe } from './log';

// As in the official docs example, keep each item's DOM node in a Map
export function CatList({ cats }: { cats: string[] }) {
  const itemsRef = useRef<Map<string, HTMLLIElement | null>>(new Map());
  const map = itemsRef.current;
  probe.map = map; // for testing
  return (
    <ul>
      {cats.map((cat) => (
        <li
          key={cat}
          ref={(node) => {
            map.set(cat, node);
            return () => {
              map.delete(cat);
            };
          }}
        >
          {cat}
        </li>
      ))}
    </ul>
  );
}

I removed and added items while recording the contents of the Map. These are the React 19 results:

text
[F. 項目ごとの DOM ノードを Map で持つ]
  1. Neo, Millie, Bella を表示
    map size=3 { Neo=<li>, Millie=<li>, Bella=<li> }
  2. Millie を消す
    map size=2 { Neo=<li>, Bella=<li> }
  3. Bella を消す
    map size=1 { Neo=<li> }
  4. Luna を足す
    map size=2 { Neo=<li>, Luna=<li> }

On React 18, the removed items stayed in the Map as null. I omitted step 1, since it matched React 19, and I also omitted the warning lines.

text
  2. Millie を消す
    map size=3 { Neo=<li>, Millie=null, Bella=<li> }
  3. Bella を消す
    map size=3 { Neo=<li>, Millie=null, Bella=null }
  4. Luna を足す
    map size=4 { Neo=<li>, Millie=null, Bella=null, Luna=<li> }

React 18 does not call the returned function. It calls the callback with null instead. So null was passed to map.set(cat, node), and the removed items were left in the Map.

Here is the same CatList running in Chromium. I started with four cats (Neo, Millie, Bella, and Luna) and removed the first cat three times. React 18 is on top and React 19 is below.

Screen showing the same CatList on React 18 and 19 stacked vertically, with the Map size and contents after pressing the remove-first-cat button three times
The result of pressing the remove-first-cat button three times. React 18: the Map size stays at 4 and the removed cats remain as null. React 19: the size drops 3, 2, 1

It also works with refs from useImperativeHandle

According to the announcement, cleanup functions work not only for DOM refs but also for class component refs and useImperativeHandle. I tested a child that passes { reset } through useImperativeHandle, with the parent passing a callback that returns a cleanup function.

tsx
import { useImperativeHandle, type Ref } from 'react';
import { log } from './log';

type CounterHandle = { reset: () => void };

// Child that passes a custom object, not a DOM node, to the ref via useImperativeHandle
function Counter({ ref }: { ref?: Ref<CounterHandle> }) {
  useImperativeHandle(ref, () => ({ reset: () => {} }), []);
  return <p>counter</p>;
}

export function HandleParent() {
  return (
    <Counter
      ref={(handle) => {
        log(`ref ${handle ? `{ ${Object.keys(handle).join(', ')} }` : 'null'}`);
        return () => {
          log('cleanup');
        };
      }}
    />
  );
}
text
[E. useImperativeHandle の ref に後片付けの関数を返す]
  1. 描画
    ref { reset }
  2. 削除
    cleanup

The callback received the object created by useImperativeHandle, and on removal the returned function was called. This child receives ref as a prop, which is the React 19 style, so on React 18 the ref never arrived and neither function was called. I did not test class component refs this time.

In TypeScript, a callback that returns a value is an error

Because a cleanup function can now be returned, the React 19 types report an error when a ref callback returns something other than a function. The announcement says the usual fix is to stop using the expression form of an arrow function. I checked this with the following file.

tsx
let instance: HTMLDivElement | null = null;

// 1st: an arrow function with an expression body that assigns and returns the value
export const A = () => <div ref={(current) => (instance = current)} />;
// 2nd: with a block body, nothing is returned
export const B = () => <div ref={(current) => { instance = current; }} />;
text
src/TypeError.tsx(4,29): error TS2322: Type '(current: HTMLDivElement | null) => HTMLDivElement | null' is not assignable to type 'Ref<HTMLDivElement> | undefined'.
  Type '(current: HTMLDivElement | null) => HTMLDivElement | null' is not assignable to type '(instance: HTMLDivElement | null) => void | (() => VoidOrUndefinedOnly)'.
    Type 'HTMLDivElement | null' is not assignable to type 'void | (() => VoidOrUndefinedOnly)'.
      Type 'null' is not assignable to type 'void | (() => VoidOrUndefinedOnly)'.
tsc exit=1

The only error is on line 4. Line 6, written with a block body, passed. The expression (instance = current) returns the assigned value, so at the type level TypeScript cannot tell whether you meant to return a cleanup function.

There is also a codemod that applies the same fix in bulk. I ran the no-implicit-ref-callback-return rule from types-react-codemod, which the announcement mentions, on this file.

text
$ npx types-react-codemod no-implicit-ref-callback-return target
text
4c4,6
< export const A = () => <div ref={(current) => (instance = current)} />;
---
> export const A = () => <div ref={current => {
>   (instance = current);
> }} />;

Line 4 was rewritten to the block form. After the rewrite, the file passed the type check (tsc exit=0). Line 6 was unchanged.

Point

In React 19, a function returned from a ref callback is called when the element is removed. If you return a function, the callback is no longer called with null. If you do not return a function, the callback is still called with null, as before. To avoid calling it on every re-render, pass the same function with useCallback.

​Posted by 86