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 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 | |
} |
One more option to the initial value being true or false debate:
const useIsMounted = (initialValue = true) => {
const ref = useRef(initialValue)
useEffect(() => {
ref.current = true
return () => {
ref.current = false
}
}, [])
return ref
}
Let that value be passed in. If true
then it behaves like its mounted initially and only changes to false
when it's unmounted. Useful to stop yourself from setting state when an async action is done after a component was unmounted. But if false
then it's treated like the original solution where it still flips to false
when unmounted but also flips to true
when ready in the client.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@zmeyc Thank you for the clarification! I tested with a delayed API calls and found that you are right. As you pointed out, it only reflected the initial mount status hook call. All this time, I was under the assumption that isMounted would return the useRef value at the time of the API request. When I pass the function isMounted() to call during the API return, it does provide the correct mounted value when my test component mounted and unmounted. Thanks again cheers!