DEV Community

Discussion on: Easily Detect Outside Click Using useRef Hook in React

Collapse
 
milichev profile image
Vadym Milichev

Neat and refreshing approach! :)

Please confirm if the following makes sense:

In the App component, a new instance of the callback function is created on each render:

    const modalRef = useOnClickOutsideRef(() => setIsOpen(false))
Enter fullscreen mode Exit fullscreen mode

In the useOnClickOutsideRef hook, the passed callback is used as a dependency of the effect:

  }, [callback]) <--
  return elementRef
}
Enter fullscreen mode Exit fullscreen mode

Thus, the window.click is unmounted and mounted again each time the component that calls useOnClickOutsideRef is rendered.

Providing the useMemo-wrapped callback ensures the same function is passed down the hook:

// App
    const modalRef = useOnClickOutsideRef(useMemo(() => setIsOpen(false), []));
Enter fullscreen mode Exit fullscreen mode
Collapse
 
pbteja1998 profile image
Bhanu Teja Pachipulusu

Yes, you are right. I missed that.