Documentation Index
Fetch the complete documentation index at: https://mintlify.com/kokonut-labs/kokonutui/llms.txt
Use this file to discover all available pages before exploring further.
A React hook that triggers a callback when a click occurs outside a specified element. Perfect for closing dropdowns, modals, and popovers.
Installation
This hook can be installed via the CLI:- Tab Title
- Tab Title
- Tab Title
bunx --bun shadcn@latest add @kokonutui/use-click-outside
/hooks/use-click-outside.ts into your project.
Usage
API Reference
Parameters
| Parameter | Type | Description |
|---|---|---|
ref | RefObject<HTMLElement> | React ref pointing to the element to monitor |
handler | () => void | Callback function to execute when a click outside is detected |
Return Value
This hook doesn’t return any value. It sets up an effect that listens for clicks.Features
- Simple API - Just pass a ref and a handler
- Automatic cleanup - Event listeners are properly removed on unmount
- Performance optimized - Uses mousedown event for faster response
Use Cases
- Closing dropdown menus when clicking outside
- Dismissing modals and popovers
- Closing mobile navigation menus
- Deselecting items when clicking away
- Hiding tooltips and context menus
Notes
- The hook uses
mousedownevent instead ofclickfor better UX - Make sure to memoize your handler function if it has dependencies to avoid unnecessary re-renders
- The ref must be attached to a DOM element before the hook can function