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
12345678910111213141516171819202122232425262728
import { RefObject, useEffect, useRef } from 'react';

const events = [`mousedown`, `touchstart`, `mouseup`, `touchend`];

type useClickOutsideProps = {
  ref: RefObject<HTMLElement | undefined>;
  callback: () => void;
};

export const useOutsideClick = ({ ref, callback }: useOutsideClickProps) => {
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent | TouchEvent) => {
      if (ref.current && !ref.current.contains(event.target as Node)) {
        callback();
      }
    };

    for (const event of events) {
      document.addEventListener(event, handleClickOutside);
    }

    return () => {
      for (const event of events) {
        document.removeEventListener(event, handleClickOutside);
      }
    };
  }, [callback]);
};