Handle Outside Clicks in React with TypeScript
Detecting a click outside of a React component is a common requirement, especially when dealing with dropdowns, modals, or tooltips that should close when a user clicks outside of them.
useOutsideClick hook
ts
1 import { RefObject, useEffect, useRef } from 'react';23 const events = [`mousedown`, `touchstart`, `mouseup`, `touchend`];45 type useClickOutsideProps = {6 ref: RefObject<HTMLElement | undefined>;7 callback: () => void;8 };910 export const useOutsideClick = ({ ref, callback }: useOutsideClickProps) => {11 useEffect(() => {12 const handleClickOutside = (event: MouseEvent | TouchEvent) => {13 if (ref.current && !ref.current.contains(event.target as Node)) {14 callback();15 }16 };1718 for (const event of events) {19 document.addEventListener(event, handleClickOutside);20 }2122 return () => {23 for (const event of events) {24 document.removeEventListener(event, handleClickOutside);25 }26 };27 }, [callback]);28 };