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
ref
withref.current
when needed , simply by callingisMounted()
, if you want to directly return theref
you just have to make sure to return all theref
and not justref.current
because if you passref.current
you will pass just the actual value and not themutable ref object
hence its value will always be stuck tofalse
. Returning theref
forces you to then read every time the.current
property, 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.