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
1import { useClickAway } from "@/hooks/use-click-away"

React TSX
1function Dropdown() {
2  const [isOpen, setIsOpen] = useState(false);
3  const ref = useRef(null);
4  
5  useClickAway(ref, () => {
6    if (isOpen) setIsOpen(false);
7  });
8  
9  return (
10    <div ref={ref}>
11      <button onClick={() => setIsOpen(!isOpen)}>Toggle Dropdown</button>
12      {isOpen && (
13        <div className="">
14          {/*Content here*/}
15        </div>
16      )}
17    </div>
18  );
19}

API Reference

React TSX
1function useClickAway(
2  ref: React.RefObject<HTMLElement | null>,
3  handler: (event: MouseEvent | TouchEvent) => void
4): void

Inputs

  • ref: A React ref object pointing to the DOM element to track clicks outside of
  • handler: 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