JAVASCRIPT

Detect Clicks Outside an Element with useClickOutside Hook

Custom React hook `useClickOutside` helps components like dropdowns or modals close automatically when a user clicks anywhere outside their boundaries.

import { useEffect, useRef } from 'react';

function useClickOutside(handler) {
  const ref = useRef();

  useEffect(() => {
    const listener = (event) => {
      if (!ref.current || ref.current.contains(event.target)) {
        return;
      }
      handler(event);
    };

    document.addEventListener('mousedown', listener);
    document.addEventListener('touchstart', listener);

    return () => {
      document.removeEventListener('mousedown', listener);
      document.removeEventListener('touchstart', listener);
    };
  }, [ref, handler]);

  return ref;
}
How it works: This hook takes a `handler` function and returns a `ref`. You should attach this `ref` to the DOM element you want to monitor (e.g., a dropdown container). The `useEffect` hook adds global event listeners for `mousedown` and `touchstart`. If a click or touch occurs on the document *outside* the element referenced by `ref.current`, the provided `handler` function is called, allowing you to close or hide the component. The listeners are automatically cleaned up when the component unmounts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs