Created
February 21, 2019 06:22
-
-
Save jaydenseric/a67cfb1b809b1b789daa17dfe6f83daa to your computer and use it in GitHub Desktop.
A React hook that tells if the component is mounted.
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' | |
export const useIsMounted = () => { | |
const ref = React.useRef(false) | |
const [, setIsMounted] = React.useState(false) | |
React.useEffect(() => { | |
ref.current = true | |
setIsMounted(true) | |
return () => (ref.current = false) | |
}, []) | |
return () => ref.current | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One more option to the initial value being true or false debate:
Let that value be passed in. If
true
then it behaves like its mounted initially and only changes tofalse
when it's unmounted. Useful to stop yourself from setting state when an async action is done after a component was unmounted. But iffalse
then it's treated like the original solution where it still flips tofalse
when unmounted but also flips totrue
when ready in the client.