New Jun 12, 2025

Why does React Strict Mode preserve component state on unmount/remount?

Libraries, Frameworks, etc. All from Newest questions tagged reactjs - Stack Overflow View Why does React Strict Mode preserve component state on unmount/remount? on stackoverflow.com

I'm observing a behavior in React's Strict Mode that seems counter-intuitive to my understanding of the component lifecycle.

My expectation is that when a component unmounts, its local state (created with useState) should be completely destroyed. However, in a Strict Mode environment, when a component is unmounted and then immediately remounted as part of Strict Mode's check, the previous state is preserved.

Here is a minimal reproducible example to demonstrate the issue:

https://codesandbox.io/p/sandbox/l6y8kh

import { useState, useEffect } from "react";

function Counter() { const [count, setCount] = useState(0);

useEffect(() => { console.log("Counter component mounted");

setCount((prev) => { console.log("prev", prev); return prev + 1; });

return () => { console.log("Counter component unmounted - cleanup function called"); }; }, []);

const handleIncrement = () => { setCount((prev) => { console.log("Previous count:", prev); return prev + 1; }); };

return ( <div className="counter"> <h2>Count: {count}</h2> <button onClick={handleIncrement}>Count Up</button> </div> ); }

function App() { const [theKey, setTheKey] = useState(1);

useEffect(() => { setTimeout(() => { alert("key is changed. so component will be unmount and re-mount"); setTheKey(2); }, 3000); }, []);

return ( <div className="App"> <h1> React Strict Mode Unmount Test. Why prev state is preserved even unmounted ? </h1> <Counter key={theKey} /> </div> ); }

export default App;

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";

import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <App />
  </StrictMode>
);
Scroll to top