8
Hooks

useClickOutside

A hook that detects clicks outside of an element and triggers a callback function.

useClickOutside

The useClickOutside hook detects clicks outside of a specified element and triggers a callback function when they occur. This hook is useful for implementing interactive UI components like modals, dropdowns, and tooltips that should close when users click outside of them.

Outside clicks detected: 0

Popup is closed

Installation

Install the useClickOutside hook using:

npx axionjs-ui add hook use-click-outside

File Structure

use-click-outside.ts

Parameters

PropTypeDefault
callback
() => void
Required
exceptRefs
RefObject<HTMLElement>[]
[]

Return Value

PropTypeDefault
ref
RefObject<T>
-

Examples

Create a dropdown menu that closes when clicking outside:

Multiple Interactive Areas

Manage multiple areas that can be clicked outside of independently:

Click to activate

Click to activate

Click on an area to activate it

Excluding Elements from Outside Clicks

In some cases, you may want to exclude certain elements from being considered “outside” clicks:

function PopoverWithTrigger() {
  const [isOpen, setIsOpen] = useState(false);
  
  // Ref for the button that toggles the popover
  const buttonRef = useRef(null);
  
  // Exclude buttonRef from outside clicks
  const popoverRef = useClickOutside(() => {
    if (isOpen) setIsOpen(false);
  }, [buttonRef]);
  
  return (
    <div>
      <button 
        ref={buttonRef}
        onClick={() => setIsOpen(!isOpen)}
      >
        Toggle Popover
      </button>
      
      {isOpen && (
        <div ref={popoverRef} className="popover">
          <p>This popover won't close when you click the toggle button</p>
        </div>
      )}
    </div>
  );
}

Use Cases

  • Modals & Dialogs: Close when clicking on the backdrop
  • Dropdown Menus: Collapse when clicking outside
  • Popovers & Tooltips: Hide when clicking elsewhere
  • Flyout Navigation: Close navigation panels on outside clicks
  • Context Menus: Dismiss right-click menus when clicking away
  • Selection Panels: Deselect active elements when clicking elsewhere
  • Rich Text Editors: Close formatting popups when clicking outside
  • Date Pickers: Hide calendar views when clicking outside

Accessibility

When implementing components with the useClickOutside hook, consider these accessibility improvements:

  • Ensure keyboard users can also close components (e.g., with Escape key)
  • Maintain proper focus management when opening/closing elements
  • Include appropriate ARIA attributes like aria-expanded and aria-haspopup
  • Trap focus inside modal components when open
  • Test your components with screen readers and keyboard navigation

Event Handling

The hook uses both mousedown and touchstart events to ensure compatibility with both mouse and touch devices. These events are chosen over click because they fire earlier in the interaction process, which often provides a better user experience.

Multiple Elements

If you need to detect clicks outside multiple elements or have complex logic, you can:

  1. Use the exceptRefs parameter to exclude specific elements
  2. Create multiple instances of the hook with different callbacks
  3. Combine with other hooks like useContext to share state

Best Practices

  • Always provide a clean way to close components besides clicking outside (e.g., Close button, Escape key)
  • Use appropriate CSS z-index values to ensure your clickable elements are properly stacked
  • Consider touch and mobile experiences where “outside” clicks may be less intuitive
  • Combine with animations for smoother transitions when opening/closing elements
  • Avoid using this hook for critical functionality that must be accessible to all users
  • Clean up event listeners properly by including the cleanup function in useEffect

On this page