DEV Community

Max Frolov
Max Frolov

Posted on

React Hook that helps understand whether component mounted

I use this hook a lot, so maybe somebody is looking for the same solution.

export const useIsMounted = () => {
  const isMountedRef = React.useRef(false)

  React.useEffect(() => {
    isMountedRef.current = true

    return () => {
      isMountedRef.current = false
    }
  }, [])

  return isMountedRef.current
}

Top comments (2)

Collapse
 
devdufutur profile image
Rudy Nappée

Nice trick ! Can you tell some use cases because I don't really understand the purpose. If I need to know if a Component is mounted, I look for it in DOM, isn't it ?

Collapse
 
max_frolov_ profile image
Max Frolov

There are specific cases when it is necessary to understand whether the component is mounted or not outside the useEffect method, for example, in some functions that can be called in child components before the parent component is mounted. Sometimes it's useful to control 3d party libs initialization. I saw a lot of people use a state to handle such behavior, but it's not a good approach and leads to unnecessary re-render.