JAVASCRIPT
Custom Hook: useClickOutside for Detecting External Clicks
Create a useClickOutside custom React hook to efficiently detect clicks that occur outside a referenced DOM element, ideal for closing modals or dropdowns.
import { useEffect, useRef } from 'react';
function useClickOutside(callback) {
const ref = useRef(null);
useEffect(() => {
const handleClickOutside = (event) => {
if (ref.current && !ref.current.contains(event.target)) {
callback();
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [callback]);
return ref;
}
// Example Usage:
// function Dropdown() {
// const [isOpen, setIsOpen] = useState(false);
// const dropdownRef = useClickOutside(() => 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 takes a callback function and returns a ref. Attach this ref to the DOM element you want to monitor. When a click occurs anywhere on the document *outside* this element, the provided callback function is executed. This is perfect for closing modals, dropdowns, tooltips, or any UI element that should disappear when the user clicks elsewhere.