JAVASCRIPT
Create a `useClickOutside` Hook for Modals or Dropdowns
Learn how to build a custom React hook, `useClickOutside`, to detect clicks outside a specified DOM element, perfect for closing modals, dropdowns, or popovers.
import { useEffect, useRef } from 'react';
function useClickOutside(handler) {
const domNodeRef = useRef();
useEffect(() => {
const maybeHandler = (event) => {
if (!domNodeRef.current || !domNodeRef.current.contains(event.target)) {
handler();
}
};
document.addEventListener('mousedown', maybeHandler);
return () => {
document.removeEventListener('mousedown', maybeHandler);
};
}, [handler]);
return domNodeRef;
}
How it works: The `useClickOutside` hook provides a way to detect when a user clicks outside of a referenced DOM element. It uses `useRef` to create a mutable reference that can be attached to any React component's DOM node. The `useEffect` hook sets up a global `mousedown` event listener on the document. When a click occurs, it checks if the clicked target is outside the referenced element using `contains()`. If it is, the provided `handler` function is called. The `useEffect` also includes a cleanup function to remove the event listener, preventing memory leaks.