Detect clicks outside of a component
Quick Answer
useClickOutside attaches mousedown and touchstart listeners to the document and calls a handler whenever the event originates outside the referenced element. It is the standard pattern for closing dropdowns and modals on outside click.
1import { useEffect, RefObject } from 'react';
2
3function useClickOutside(
4 ref: RefObject<HTMLElement>,
5 handler: (event: MouseEvent | TouchEvent) => void
6) {
7 useEffect(() => {
8 const listener = (event: MouseEvent | TouchEvent) => {
9 if (!ref.current || ref.current.contains(event.target as Node)) {
10 return;
11 }
12 handler(event);
13 };
14
15 document.addEventListener('mousedown', listener);
16 document.addEventListener('touchstart', listener);
17
18 return () => {
19 document.removeEventListener('mousedown', listener);
20 document.removeEventListener('touchstart', listener);
21 };
22 }, [ref, handler]);
23}useClickOutside attaches mousedown and touchstart listeners to the document and calls your handler whenever the event target is outside the referenced element. This is the standard pattern for closing dropdowns, modals, pop-overs, and context menus when the user clicks elsewhere on the page.
mousedown fires before the browser processes the click, so you can close the dropdown before any click handler on the trigger button re-opens it.
Yes. Portals still propagate events through the React tree, so the contains check on the DOM element works correctly.
Yes, as long as each nested element has its own ref. The contains method handles any depth of nesting.
This free typescript code snippet for useclickoutside hook is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this intermediate-level example will help you implement useclickoutside hook quickly and correctly.
All snippets in the Snippetly library follow typescript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses typescript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.