Al establecer el estado después de que se desmontó un componente, React debería registrar el siguiente 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.Sin embargo, si devuelvo una función vacía como función de limpieza, no registrará el error.
el código:
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> ); }