useOutsideClick

React hook to detect clicks outside of a specified component.

import { useEffect, MutableRefObject } from 'react'

export const useOutsideClick = (
  ref: MutableRefObject<HTMLElement | null>,
  fn: () => void,
) => {
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (ref.current && !ref.current.contains(event.target as Node)) {
        fn()
      }
    }

    document.addEventListener('click', handleClickOutside)

    return () => {
      document.removeEventListener('click', handleClickOutside)
    }
  }, [ref, fn])
}

React 16.8 or higher

  • Name
    ref
    Type
    HTMLElement | null
    Required
    required
    Description

    The DOM element to detect clicks outside of.

  • Name
    fn
    Type
    function
    Required
    required
    Description

    A callback function to execute when a click outside the referenced element is detected.

import { useState, useRef } from 'react'
import { useOutsideClick } from './hooks/useOutsideClick'

const DropdownMenu = () => {
  const [isOpen, setIsOpen] = useState(false)
  const dropdownRef = useRef<HTMLDivElement>(null)

  const toggleMenu = () => {
    setIsOpen(!isOpen)
  }

  const closeMenu = () => {
    setIsOpen(false)
  }

  useOutsideClick(dropdownRef, closeMenu)

  return (
    <div ref={dropdownRef}>
      <button onClick={toggleMenu}>Toggle Dropdown</button>
      {isOpen && (
        <div>
          <ul>
            <li>Option 1</li>
            <li>Option 2</li>
            <li>Option 3</li>
          </ul>
        </div>
      )}
    </div>
  )
}

export default DropdownMenu

Here are some use cases where this React hook is useful:

  • Closing dropdown menus when clicking outside
  • Dismissing modal dialogs when clicking outside
  • Hiding context menus on outside click