useClickOutside
React hook that detects clicks outside of a referenced element. Perfect for modals, dropdowns, and sidebars.
Overview
useClickOutside is a React hook that detects when a user clicks outside of a specific element. Unlike the traditional implementation where you pass a ref, this hook returns a ref that you can attach to any element you want to monitor.
Demo
react-hooks-ts
useClickOutside
Detects clicks outside a referenced element. Perfect for closing dropdowns, modals, and popovers.
Outside clicks detected:
0
Dropdown Menu
Click outside the dropdown to close it
Modal Dialog
Click outside the modal content to close it
API Reference
function useClickOutside<T extends HTMLElement>(
handler: () => void
): RefObject<T | null>Parameters
| Name | Type | Description |
|---|---|---|
handler | () => void | Callback function to run when an outside click is detected |
Returns
| Type | Description |
|---|---|
RefObject<T | null> | A React ref to be attached to the target element |
Usage Examples
Basic Dropdown
import { useState } from 'react'
import { useClickOutside } from 'react-hooks-ts'
function Dropdown() {
const [isOpen, setIsOpen] = useState(false)
const ref = useClickOutside<HTMLDivElement>(() => setIsOpen(false))
return (
<div ref={ref}>
<button onClick={() => setIsOpen(!isOpen)}>Toggle</button>
{isOpen && (
<ul className="dropdown-menu">
<li>Option 1</li>
<li>Option 2</li>
</ul>
)}
</div>
)
}Closing a Modal
const closeModal = () => setShowModal(false)
const modalRef = useClickOutside<HTMLDivElement>(closeModal)
return (
<div className="overlay">
<div ref={modalRef} className="modal-content">
<h2>Modal Content</h2>
<button onClick={closeModal}>Close</button>
</div>
</div>
)Features
- ✅ Modern API - Returns the ref for a cleaner developer experience
- 📱 Mobile Ready - Full support for
touchstartevents - 🧩 TypeScript - Fully typed with generic support for any HTML element
- 🛡️ SSR Safe - Works perfectly in Next.js and other SSR environments
- ⚡ Optimized - Handles event listener cleanup automatically