JAVASCRIPT

Detect Clicks Outside a Component with useClickOutside

Build a custom React hook to detect clicks occurring outside a specified DOM element, perfect for closing modals, dropdowns, or tooltips automatically.

import { useEffect } from 'react';

function useClickOutside(ref, callback) {
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (ref.current && !ref.current.contains(event.target)) {
        callback();
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [ref, callback]);
}
How it works: The `useClickOutside` hook attaches a global `mousedown` event listener to the document. When a click occurs, it checks if the clicked element is outside the provided `ref`'s current DOM element. If it is, the `callback` function is invoked. This is commonly used for dismissing UI elements like dropdowns, sidebars, or modal dialogs when a user clicks anywhere else on the page, enhancing interactivity.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs