react: Bug: in , useEffect cleanup is called for the second mount, not the first one

Link to code example: https://playcode.io/1986248?v=2 React version: 18.0.0

I have a feeling that this was described one way or another, so I’ll keep this one minimalistic and straight to the point.

Let’s suppose we have some Disposable object we want to initialize when component mounts and destroy when component unmounts:

let globalCounter = 0;

const useCounter = () => {
  const [counter] = useState(() => globalCounter++);

  useEffect(() => {
    return () => {
      console.log('clean counter', counter);
    };
  }, []);

  return counter;
};

Let’s render this component in strict mode, while looking at render/cleanup order (imports, createRoot and <StrictMode> omitted):

function App() {
  const counter = useCounter();
  console.log('rendering counter', counter);

  return <div>current counter {counter}</div>;
}

The current console output

rendering counter 0
rendering counter 1
clean counter 1           // why 1 and not 0?

And the App is obviously rendering div with current counter 1

The expected console output

It’s either first counter cleanup instead of the second one:

rendering counter 0
rendering counter 1
clean counter 0 // <-- this is different

Or the same, but before the second render:

rendering counter 0
clean counter 0 // <-- moved here
rendering counter 1

The problem

The render proceeds with the second counter, which is “disposed”, while the first counter is just “left hanging”

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 3
  • Comments: 17 (3 by maintainers)

Most upvoted comments

The issue you’re encountering relates to React’s Strict Mode, which intentionally triggers certain lifecycle methods (including useEffect cleanups) twice to help developers identify potential side effects in their components. This is particularly relevant in React 18 and newer versions.

Explanation Strict Mode in React 18: When you use StrictMode in React, it intentionally unmounts and remounts components to detect side effects. This means that useEffect cleanups may be triggered more than once, even if the component hasn’t been visibly removed from the UI.

Double Rendering: In your example, the first useEffect cleanup (clean counter 0) happens, but before the cleanup is logged, React immediately triggers another render of the component, assigning a new counter value (counter 1). However, the cleanup log shows clean counter 1 because React has already moved on to the next render cycle.

Expected Behavior in Strict Mode Given the intentional behavior of Strict Mode:

The initial render (counter 0) occurs. React triggers a cleanup, but since the component re-renders immediately, the counter state increments to 1. The cleanup log shows clean counter 1 because React is now dealing with the most recent state. How to Handle It If you want to observe the cleanup of the first render, you might consider disabling Strict Mode or understanding that this behavior is a part of React’s effort to make components more resilient. React’s double invocation of certain lifecycle methods (including useEffect cleanups) is designed to catch potential issues in components.

@gianlucadifrancesco @LoganDark damn guys you were right. The example with counter was misleading. I rewrote it without global variable and the order is correct: https://playcode.io/1994448

function useSecondsSinceMount() {
  const [seconds, setSeconds] = useState(0);
  const [intervalId, setIntervalId] = useState(null)

  useEffect(() => {
    const id = setInterval(() => {
      setSeconds((current) => current + 1);
    }, 1000);

    console.log("set interval", id);
    setIntervalId(id)

    return () => {
      console.log("clean up interval", id);
      clearInterval(id);
    };
  }, []);

  return [seconds, intervalId];
}

export default function App() {
  const [seconds, intervalId] = useSecondsSinceMount();

  return (
    <div className="App">
      <h2>Seconds since component mount: {seconds}</h2>
      {intervalId && (
        <h3>Used interval: {intervalId}</h3>
      )}
    </div>
  );
}