Sometimes, we want to clean up memory leaks on an unmounted component in React Hooks.
In this article, we’ll look at how to clean up memory leaks on an unmounted component in React Hooks.
How to clean up memory leaks on an unmounted component in React Hooks?
To clean up memory leaks on an unmounted component in React Hooks, we use the useMountedState
hook from the react-use
package.
To install it, we run
npm i react-use
Then in our component, we add
const isMounted = useMountedState();
useEffect(() => {
const asyncAction = executeAsyncAction();
asyncAction.then((result) => {
if (isMounted) {
// ...
}
});
}, []);
to call the useMountedState
hook to return a boolean to indicate if the component is mounted.
And then we check isMounted
in the useEffect
callback before we do anything.
Conclusion
To clean up memory leaks on an unmounted component in React Hooks, we use the useMountedState
hook from the react-use
package.