← Back to all snippets
JAVASCRIPT

Detect Clicks Outside an Element with `useClickOutside`

Implement a `useClickOutside` React hook to detect when a user clicks anywhere outside a specified DOM element, useful for closing modals, dropdowns, and context menus.

import { useEffect, useRef } from 'react';

function useClickOutside(callback) {
  const ref = useRef(null);

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

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [callback]);

  return ref;
}

// Example Usage:
/*
function Dropdown() {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useClickOutside(() => setIsOpen(false));

  return (
    <div ref={dropdownRef} style={{ border: '1px solid black', padding: '10px' }}>
      <button onClick={() => setIsOpen(!isOpen)}>Toggle Dropdown</button>
      {isOpen && (
        <div style={{ background: 'lightgray', padding: '10px', marginTop: '5px' }}>
          Dropdown Content
        </div>
      )}
    </div>
  );
}
*/
How it works: The `useClickOutside` hook provides a `ref` that you attach to the element you want to monitor. It then attaches a global `mousedown` event listener to the document. When a click occurs, it checks if the clicked target is *outside* the referenced element. If it is, the provided `callback` function is executed. This is commonly used to close UI components like dropdowns, modals, or sidebars when a user clicks away from them.

Need help integrating this into your project?

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

Hire DigitalCodeLabs