Back to Snippets
ReactTypeScript

React useClickOutside Hook

Detects clicks outside a referenced element to close dropdowns or modals.

reacthookclickdropdown
import { useEffect, useRef } from class=class="text-emerald-400">"text-emerald-400">'react'

function useClickOutside<T extends HTMLElement>(callback: () => void) {
  const ref = useRef<T>(null)

  useEffect(() => {
    function handleClick(event: MouseEvent) {
      if (ref.current && !ref.current.contains(event.target as Node)) {
        callback()
      }
    }

    document.addEventListener(class=class="text-emerald-400">"text-emerald-400">'mousedown', handleClick)
    return () => document.removeEventListener(class=class="text-emerald-400">"text-emerald-400">'mousedown', handleClick)
  }, [callback])

  return ref
}

export default useClickOutside

How to Use

Attach to a dropdown container: const ref = useClickOutside<HTMLDivElement>(() => setOpen(false)). Pass the ref to the wrapper element. Clicking outside will trigger the callback.

Related Technology

React

Have a Project in Mind?

Let's discuss how we can bring your idea to life. From initial concept to production-ready product — we've got you covered.

or book a free call