JAVASCRIPT
Detect Clicks Outside a React Component
Create a custom React hook `useClickOutside` to easily detect clicks that occur outside a specific DOM element, useful for closing modals or dropdowns.
import { useEffect } 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]); // Reload only if ref or handler changes
}
How it works: The `useClickOutside` hook takes a React ref and a callback function. It attaches event listeners to the `document` to detect `mousedown` and `touchstart` events. If the click or touch occurs outside the element referenced by `ref`, the provided `handler` function is executed. This is commonly used for closing dropdowns, modals, or sidebars when a user clicks anywhere else on the page.