JAVASCRIPT

React useClickOutside Hook for Modals and Dropdowns

Learn to create a React useClickOutside custom hook to detect clicks outside a specific element, perfect for closing modals, dropdowns, or popovers.

import { useEffect, useRef } from 'react';

function useClickOutside(handler) {
  const domNode = useRef();

  useEffect(() => {
    const maybeHandler = (event) => {
      if (!domNode.current?.contains(event.target)) {
        handler();
      }
    };

    document.addEventListener('mousedown', maybeHandler);

    return () => {
      document.removeEventListener('mousedown', maybeHandler);
    };
  }, [handler]);

  return domNode;
}

// Usage example:
// function MyComponent() {
//   const [isOpen, setIsOpen] = useState(false);
//   const ref = useClickOutside(() => setIsOpen(false));

//   return (
//     <div ref={ref} style={{ border: '1px solid black', padding: '20px' }}>
//       <button onClick={() => setIsOpen(!isOpen)}>Toggle Dropdown</button>
//       {isOpen && (
//         <div style={{ background: 'lightgray', padding: '10px', marginTop: '10px' }}>
//           Dropdown Content
//         </div>
//       )}
//     </div>
//   );
// }
How it works: This custom hook detects clicks that occur outside of the DOM element it's attached to. It uses `useRef` to create a mutable reference to the DOM node and `useEffect` to attach and clean up a global `mousedown` event listener. When a click happens, it checks if the clicked target is within the referenced node. If not, it calls the provided `handler` function, typically used to close a modal or dropdown.

Need help integrating this into your project?

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

Hire DigitalCodeLabs