← Back to all snippets
JAVASCRIPT

Detect Clicks Outside a React Component with `useClickOutside`

Implement a `useClickOutside` custom hook in React to detect clicks outside a specific DOM element, ideal for closing modals, dropdowns, or popovers automatically.

import { useEffect, useRef } from 'react';

function useClickOutside(ref, handler) {
  useEffect(() => {
    const listener = (event) => {
      // Do nothing if clicking ref's element or descendent 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 Dropdown() {
//   const [isOpen, setIsOpen] = useState(false);
//   const dropdownRef = useRef(null);

//   useClickOutside(dropdownRef, () => {
//     if (isOpen) setIsOpen(false);
//   });

//   return (
//     <div ref={dropdownRef}>
//       <button onClick={() => setIsOpen(!isOpen)}>Toggle Dropdown</button>
//       {isOpen && (
//         <div style={{ border: '1px solid black', padding: '10px', marginTop: '5px' }}>
//           <p>Dropdown Content</p>
//         </div>
//       )}
//     </div>
//   );
// }
How it works: The `useClickOutside` hook helps detect when a user clicks anywhere outside a referenced React component. It takes a `ref` to the target component and a `handler` function as arguments. `useEffect` attaches `mousedown` and `touchstart` event listeners to the `document`. When an event occurs, it checks if the click target is outside the element referenced by `ref`. If it is, the provided `handler` function is executed. This is crucial for user interface patterns like automatically closing dropdowns, modals, or context menus when the user clicks away.

Need help integrating this into your project?

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

Hire DigitalCodeLabs