Created
May 19, 2020 01:39
-
-
Save owenconti/988dc32643f005bdb4c994b8ec777806 to your computer and use it in GitHub Desktop.
How to fix "cannot update unmounted component" warning with React hooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| React.useEffect(() => { | |
| let unmounted = false; | |
| setTimeout(() => { | |
| if (!unmounted) { | |
| // update state here... | |
| } | |
| }, 3000); | |
| return () => { | |
| unmounted = true; | |
| }; | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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