useClickAway
A custom React hook for detecting clicks outside of a specified element.
- Useful for closing modals, dropdowns, and other interactive components when clicking outside
- Supports both mouse and touch events for better mobile compatibility
- Highly optimized to prevent unnecessary re-renders
Installation
The useClickAway hook is part of our UI library. You can import it directly from the hooks directory.
Usage
Here is how to use the useClickAway hook in your project:
React TSX
React TSX
API Reference
React TSX
Inputs
ref
: A React ref object pointing to the DOM element to track clicks outside ofhandler
: The callback function that will be triggered when a click outside the referenced element is detected
Output
- The hook doesn't return any value (void)
Behavior
- When a click (
mousedown
) or touch event (touchstart
) occurs outside the referenced element, the handler is called with the original event - The hook automatically manages event listeners (adding on mount and cleaning up on unmount)
- Touch events are supported for mobile compatibility