Skip to content

Instantly share code, notes, and snippets.

@ld-web
Created December 25, 2019 11:12
Show Gist options
  • Save ld-web/917994bd10f9d305b523ae3d033b6a9a to your computer and use it in GitHub Desktop.
Save ld-web/917994bd10f9d305b523ae3d033b6a9a to your computer and use it in GitHub Desktop.
useIsMounted custom React hook
import React, { useEffect } from 'react';
/**
* useIsMounted hook can be used to check if a component is still mounted.
* Then, one can prevent a state update on an unmounted component, and therefore avoid memory leaks
*/
function useIsMounted() {
const isMounted = React.useRef(true);
useEffect(() => {
return () => {
isMounted.current = false;
};
}, []);
return isMounted;
}
export default useIsMounted;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment