← Back to all snippets
JAVASCRIPT

Detecting Clicks Outside a React Component with useClickOutside Hook

Build a custom `useClickOutside` hook in React to detect clicks occurring outside a referenced DOM element, ideal for closing modals or dropdowns.

import { useEffect } from 'react';

function useClickOutside(ref, handler) {
  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]);
}

// Example Usage:
// function DropdownMenu() {
//   const [isOpen, setIsOpen] = useState(false);
//   const dropdownRef = useRef(null);
//
//   useClickOutside(dropdownRef, () => setIsOpen(false));
//
//   return (
//     <div ref={dropdownRef} style={{ position: 'relative', display: 'inline-block' }}>
//       <button onClick={() => setIsOpen(!isOpen)}>Toggle Dropdown</button>
//       {isOpen && (
//         <div style={{ position: 'absolute', border: '1px solid black', padding: '10px' }}>
//           <p>Item 1</p>
//           <p>Item 2</p>
//         </div>
//       )}
//     </div>
//   );
// }
How it works: The `useClickOutside` hook attaches global `mousedown` and `touchstart` event listeners to the document. When an event occurs, it checks if the click originated inside the provided `ref` element. If the click is outside the `ref`, the `handler` function is executed. The `useEffect` hook ensures the listeners are properly added and removed to prevent memory leaks, making it ideal for closing modals, dropdowns, or tooltips when a user clicks elsewhere on the page.

Need help integrating this into your project?

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

Hire DigitalCodeLabs