← Back to all snippets
JAVASCRIPT

Detect Clicks Outside an Element with useOutsideClick

Implement common UI patterns like closing modals or dropdowns when clicking outside, using a custom React `useOutsideClick` hook.

import { useEffect, useRef } from 'react';

const useOutsideClick = (handler) => {
  const ref = useRef(null);

  useEffect(() => {
    const listener = (event) => {
      // Do nothing if clicking ref's element or descendant elements
      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]); // Rerun if ref or handler changes

  return ref;
};

export default useOutsideClick;
How it works: The `useOutsideClick` hook provides a mechanism to detect when a click or touch event occurs outside of a specific DOM element. It returns a `ref` that should be attached to the target element. When an outside click is detected, the provided `handler` function is invoked. This is crucial for accessibility and user experience in components like dropdowns, modals, or context menus.

Need help integrating this into your project?

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

Hire DigitalCodeLabs