Skip to content

Instantly share code, notes, and snippets.

@owenconti
Created May 19, 2020 01:39
Show Gist options
  • Select an option

  • Save owenconti/988dc32643f005bdb4c994b8ec777806 to your computer and use it in GitHub Desktop.

Select an option

Save owenconti/988dc32643f005bdb4c994b8ec777806 to your computer and use it in GitHub Desktop.
How to fix "cannot update unmounted component" warning with React hooks
React.useEffect(() => {
let unmounted = false;
setTimeout(() => {
if (!unmounted) {
// update state here...
}
}, 3000);
return () => {
unmounted = true;
};
});
import React from "react";
import ReactDOM from "react-dom";
function App() {
const [showPage, togglePage] = React.useState(true);
return (
<div>
{showPage ? <Page /> : null}
<button onClick={() => togglePage(!showPage)}>
Toggle Page component
</button>
</div>
);
}
function Page() {
const [data, setData] = React.useState(null);
React.useEffect(() => {
let unmounted = false;
console.log("Running effect to fetch data");
setTimeout(() => {
console.log("Data loaded for page");
if (!unmounted) {
setData("Some data you loaded from a server somewhere...");
}
}, 3000);
return () => {
unmounted = true;
};
}, []);
return (
<div>
<div>Data: {data}</div>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment