JAVASCRIPT

Detect Clicks Outside an Element with useOnClickOutside Hook

Implement a custom React hook to efficiently detect when a user clicks outside a specified DOM element, perfect for closing modals, dropdowns, or tooltips.

import { useEffect } from 'react';

function useOnClickOutside(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]); // Reload only if ref or handler changes
}

// Example usage:
// function Dropdown() {
//   const [isOpen, setIsOpen] = useState(false);
//   const dropdownRef = useRef();
//   useOnClickOutside(dropdownRef, () => setIsOpen(false));

//   return (
//     <div ref={dropdownRef}>
//       <button onClick={() => setIsOpen(!isOpen)}>Toggle Dropdown</button>
//       {isOpen && (
//         <div style={{ border: '1px solid black', padding: '10px', marginTop: '5px' }}>
//           Dropdown content here
//         </div>
//       )}
//     </div>
//   );
// }
How it works: The `useOnClickOutside` hook provides a robust solution for detecting clicks that occur anywhere outside of a referenced DOM element. It attaches event listeners to the document for both `mousedown` and `touchstart` events. If the click target is not inside the referenced element, the provided `handler` function is invoked. This is incredibly useful for managing UI elements like modals, dropdowns, or tooltips that should close 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