日本語

React useEffect Cleanup Timing: When the Cleanup Function Runs

​​React​Playwright,TypeScript,Vite

The cleanup function returned from React's useEffect runs when the component is removed from the screen, and right before the next setup when a value in the dependency array changes. If a re-render happens only because state that is not in the dependency array changed, it does not run. When you write clearInterval for a timer or removeEventListener for an event listener in the cleanup, knowing when it runs helps you catch missing cleanups and unexpected timing.

In a test environment, I built a component that writes one line each time setup and cleanup run. I then switched its visibility and changed a dependency value, and recorded the order in which the functions were called.

Note

The test environment was Ubuntu 24.04 and Node.js 22.23.4. I tried it in a project created with npm create vite@latest using the react-ts template (react / react-dom 19.3.1, Vite 8.3.8, TypeScript 7.0.2). I used Playwright 1.63.0 to run Chromium 153, opened the page, and pressed the buttons in order. The dev server was tested both without StrictMode and with the app wrapped in StrictMode. The production build (vite build and vite preview) was tested without StrictMode. I did not test React 18 or earlier, frameworks such as Next.js, or useLayoutEffect.

Summary table

This table shows whether the cleanup of the effect that has name in its dependency array ran when you pressed each button.

Operation Cleanup Setup after it
Hide the component (show && ... becomes false) Called (with the value just before it was removed) None
Show it again Not called Called
Change name, which is in the dependency array Called (with the old value) Called (with the new value)
Change count, which is not in the dependency array Not called Not called

Only the effect with no dependency array ran its cleanup and setup after every re-render, including when count changed.

A component that logs the order of calls

CatCard displays the name it receives and places a child component, Bell, inside it. There are three effects: one with name in the dependency array in both CatCard and Bell, and one in CatCard with no dependency array.

tsx
// src/CatCard.tsx
import { useEffect } from 'react';
import { log } from './log';

function Bell({ name }: { name: string }) {
  useEffect(() => {
    log(`子 Bell セットアップ(${name})`);
    return () => log(`子 Bell 後片付け(${name})`);
  }, [name]);
  return <span>🔔</span>;
}

export default function CatCard({ name, count }: { name: string; count: number }) {
  useEffect(() => {
    log(`CatCard セットアップ(${name})`);
    return () => {
      const shown = document.getElementById('cat-name')?.textContent ?? '(画面にない)';
      log(`CatCard 後片付け(${name})/このとき画面の名前:${shown}`);
    };
  }, [name]);

  useEffect(() => {
    log(`依存配列なし セットアップ(count=${count})`);
    return () => log(`依存配列なし 後片付け(count=${count})`);
  });

  return (
    <p>
      <span id="cat-name">{name}</span> <Bell name={name} />(count={count})
    </p>
  );
}

In the cleanup of CatCard, I also read the name currently shown on the screen and log it. This shows whether the cleanup runs before or after the screen changes.

log writes to console.log and also appends the same line to the <ol id="log"> at the bottom of the page. To keep the logging from causing extra re-renders, it does not use React state. It appends to the DOM directly.

ts
// src/log.ts
// Writes one line each to the <ol id="log"> at the bottom of the screen and to the console (does not use React state)
let n = 0;
export function log(text: string) {
  n += 1;
  const line = `${n}. ${text}`;
  console.log(line);
  const li = document.createElement('li');
  li.textContent = text;
  document.getElementById('log')?.appendChild(li);
}

The parent App has three buttons: one to hide or show the component, one to change name (which is in the dependency array), and one to increase count (which is not). Each button press also logs a line, so you can see where in the log each press happened. The button labels in the code are in Japanese; in this article they are called Hide/Show, Change name, and Increase count.

tsx
// src/App.tsx
import { useState } from 'react';
import CatCard from './CatCard';
import { log } from './log';

export default function App() {
  const [show, setShow] = useState(true);
  const [name, setName] = useState('たま');
  const [count, setCount] = useState(0);
  return (
    <div>
      <button onClick={() => {
          log(`▶「${show ? '隠す' : '表示する'}」を押した`);
          setShow((s) => !s);
        }}>{show ? '隠す' : '表示する'}</button>
      <button onClick={() => {
          log('▶「名前を変える」を押した');
          setName((n) => (n === 'たま' ? 'みけ' : 'たま'));
        }}>名前を変える</button>
      <button onClick={() => {
          log('▶「count を増やす」を押した');
          setCount((c) => c + 1);
        }}>count を増やす</button>
      {show && <CatCard name={name} count={count} />}
    </div>
  );
}

First, I opened the page on the dev server without wrapping the app in StrictMode. I pressed Increase count, Change name, Hide, and Show, in that order. The screen after the last press was captured from the same operations on the production build.

Three buttons in a row, with the name "Mike" and a bell icon followed by "(count=1)" below them. The labels in this screenshot are in Japanese. Below that, a light blue panel lists numbered log lines from 1 to 21, with setup and cleanup lines following each button-press line
The screen after pressing the buttons four times in order (Increase count, Change name, Hide, Show). The light blue panel below shows the order in which setup and cleanup ran

The 21 lines in the panel below were the same as the log from the dev server without StrictMode. I explain each case below.

Changing a value not in the dependency array does not call the cleanup

This is the log when I pressed Increase count.

text
4. ▶「count を増やす」を押した
5. 依存配列なし 後片付け(count=0)
6. 依存配列なし セットアップ(count=1)

CatCard re-rendered because count changed, but neither of the two effects with name in the dependency array ran its cleanup or setup. Only the effect with no dependency array ran its cleanup with the old count=0, and then its setup with the new count=1. The official reference on omitting the dependency array also says that if you pass no dependency array, the effect runs after every commit (the point where React applies the render to the screen).

When a dependency changes, cleanup runs with the old value, then setup runs with the new value

This is the log when I pressed Change name, which changed name from Tama to Mike.

text
7. ▶「名前を変える」を押した
8. 子 Bell 後片付け(たま)
9. CatCard 後片付け(たま)/このとき画面の名前:みけ
10. 依存配列なし 後片付け(count=1)
11. 子 Bell セットアップ(みけ)
12. CatCard セットアップ(みけ)
13. 依存配列なし セットアップ(count=1)

Even though the component stayed on the screen, the cleanup ran. The value of name that the cleanup function read was the old Tama. The cleanup function is created during the render that set up the effect, so it keeps the values from that render. This matches the official explanation that each render has its own effects.

On the other hand, the screen name read inside the cleanup was already Mike. The cleanup runs after React has updated the DOM with the new content. The official reference on the useEffect parameters also says that when a commit changes a dependency value, React first runs the cleanup with the old values, and then runs the setup with the new values.

In this log, all three effects finished their cleanups before any setup began. The cleanup of the child Bell ran before the parent CatCard.

Hiding calls only cleanup, and showing again calls only setup

This is the log when I pressed Hide, which set show to false and removed CatCard from the screen, and then when I pressed Show to bring it back.

text
14. ▶「隠す」を押した
15. CatCard 後片付け(みけ)/このとき画面の名前:(画面にない)
16. 依存配列なし 後片付け(count=1)
17. 子 Bell 後片付け(みけ)
18. ▶「表示する」を押した
19. 子 Bell セットアップ(みけ)
20. CatCard セットアップ(みけ)
21. 依存配列なし セットアップ(count=1)

When the component was hidden, the cleanups of all three effects ran, including the child Bell, and no setup followed. When the cleanup searched for the name element, it was no longer there, so it fell back to the default text meaning "not on screen". As with a value change, the cleanup ran after the removal from the screen. Unlike the value change, the order was reversed: the parent CatCard ran first, then the child Bell.

When the component was shown again, only the setup ran, the same as when it first appears. name was still Mike because the parent App, which was not unmounted, holds the name state.

With StrictMode, cleanup is called one extra time at first

I changed main.tsx so that the whole app is wrapped in <StrictMode> only when ?strict is added to the URL. I opened that URL on the dev server and repeated the same operations. This is the log right after the page opened.

text
1. 子 Bell セットアップ(たま)
2. CatCard セットアップ(たま)
3. 依存配列なし セットアップ(count=0)
4. CatCard 後片付け(たま)/このとき画面の名前:たま
5. 依存配列なし 後片付け(count=0)
6. 子 Bell 後片付け(たま)
7. 子 Bell セットアップ(たま)
8. CatCard セットアップ(たま)
9. 依存配列なし セットアップ(count=0)

Without pressing any button, after the setup, the cleanup ran in the same order as when hiding, and then the setup ran again. When I showed the component again with Show, the order was also setup, cleanup, setup. The logs for Increase count, Change name, and Hide were the same as without StrictMode.

This only happens during development. The official reference on useEffect caveats says that in Strict Mode, React runs an extra setup and cleanup cycle during development before the first real setup. This checks whether the cleanup properly reverses what the setup did. It does not happen in production.

The official troubleshooting section also says that the cleanup runs not only when the component unmounts, but also before a re-render caused by a changed dependency. For this reason, the official docs recommend writing the cleanup not as "the code that runs when the component unmounts," but as the code that stops or undoes what the setup did. For concrete patterns, such as adding and removing event listeners, animations, and data fetching, see the official guide on handling the effect firing twice in development.

​Posted by 86