In the following example taken from usehooks-ts website
import { useCallback, useEffect, useRef } from 'react'
function useIsMounted() {
const isMounted = useRef(false)
useEffect(() => {
isMounted.current = true
return () => {
isMounted.current = false
}
}, [])
return useCallback(() => isMounted.current, [])
}
export default useIsMounted
Why do we return the isMounted.current as a callback and don't return just the value isMounted.current?
What would be an example where returning just isMounted.current as a value will be a bad idea?
You could test the different implementation yourself to see what happens:
Check the demo HERE
The usage of a callback is useful because it lets you to read directly the value of the
refwithref.currentwhen needed , simply by callingisMounted(), if you want to directly return therefyou just have to make sure to return all therefand not justref.currentbecause if you passref.currentyou will pass just the actual value and not themutable ref objecthence its value will always be stuck tofalse. Returning therefforces you to then read every time the.currentproperty, and that's not very nice, and it could mislead people using the hook without knowing the internal implementation, while callingisMounted()is nicer to read, and to use and avoids usage troubles.