How to fix "cannot update unmounted component" warning with React hooks

Published under React.

📺  Click here to skip to the video attached to this post  👇

When you attempt to update the state of a component after its been unmounted, React will warn you that you should not do that.

This can happen if you perform an asynchronous side effect (such as loading data) and then unmount the component before the asynchronous function is finished.

When using React's useEffect hook, you can keep track of whether the component is mounted and then conditionally update state. This happens within the useEffect body:

The function we return at the bottom of useEffect is called whenever the component is unmounted. This allow us to track a boolean unmounted to determine if we should update state when our asynchronous function finishes.

Check out the full example below:

Thanks for reading!

Did you find this post useful? Let me know on Twitter! If you found an issue with the content, submit a pull request!

Subscribe to my newsletter to know when I publish more content in the future.

❤️ Likes: 0
📣 Retweets: 0
💬 Replies: 0
🙊 Mentions: 0