When setting state after a component was unmounted, React should log the following error:
Warning: Can't perform a React state update on an unmounted component.
This is a no-op, but it indicates a memory leak in your application.
To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
However, If I'm returning an empty function as the cleanup function it would not log the error.
the code:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function Comp() {
const [state, setState] = useState("nothing");
useEffect(() => {
setState("loading");
sleep(1000).then(() => {
console.log("setting state");
setState("finished");
});
// When the below return exists it does not log the error
return () => {};
}, []);
return <span>{state}</span>;
}
export default function App() {
const [show, setShow] = useState(true);
useEffect(() => {
sleep(500).then(() => setShow(false));
}, []);
return (
<div className="App">
<h1>
<button onClick={() => setShow((v) => !v)}>Show</button>
{show && <Comp />}
</h1>
</div>
);
}