Created
December 25, 2019 11:12
-
-
Save ld-web/917994bd10f9d305b523ae3d033b6a9a to your computer and use it in GitHub Desktop.
useIsMounted custom React hook
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, { 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