JAVASCRIPT

useClickOutside Hook for Detecting Clicks Outside an Element

Create a `useClickOutside` React hook to detect clicks occurring outside a specified DOM element, perfect for closing dropdowns, modals, or tooltips.

import { useEffect, useRef, useState } from 'react';

const 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]); // Only re-run if ref or handler changes
};

// Example Usage:
// import React, { useRef, useState } from 'react';
// function Dropdown() {
//   const [isOpen, setIsOpen] = useState(false);
//   const dropdownRef = useRef(null);
//
//   useClickOutside(dropdownRef, () => {
//     if (isOpen) setIsOpen(false);
//   });
//
//   return (
//     <div ref={dropdownRef} style={{ position: 'relative', display: 'inline-block' }}>
//       <button onClick={() => setIsOpen(!isOpen)}>Toggle Dropdown</button>
//       {isOpen && (
//         <div style={{ position: 'absolute', top: '40px', left: '0', border: '1px solid black', padding: '10px', background: 'white' }}>
//           Dropdown Content
//         </div>
//       )}
//     </div>
//   );
// }
How it works: The `useClickOutside` hook takes a `ref` to a DOM element and a `handler` function. It attaches `mousedown` and `touchstart` event listeners to the `document`. When a click or touch occurs, it checks if the event target is inside the `ref`'s current element. If the click is outside, the `handler` function is executed. This is ideal for dismissing UI elements like dropdowns, sidebars, or tooltips when a user clicks anywhere else 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