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 | |
} |
@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!
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.
The state update is in fact an instance of the
forceUpdate
pattern.