npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

use-click-outside-react

v1.0.0

Published

Production-ready React 18 & 19 hook to detect clicks and touches outside target element(s) with Escape key support.

Readme

🎯 use-click-outside-react

Production-ready, zero-dependency React 18 & 19 hook to detect clicks and touch gestures outside element(s) with Escape key and multi-ref support.

npm version License: MIT Sponsor React 18 & 19 TypeScript


✨ Features

  • 🖱️ Pointer & Touch Support — Listens to both mousedown and touchstart for seamless desktop and mobile interactions.
  • 📚 Multi-Ref Support — Supply an array of refs (e.g. dropdown toggle button + floating menu container) to prevent accidental closes.
  • ⌨️ Escape Key Handling — Built-in closeOnEscape: true option for accessible modals, popovers, and drawers.
  • ⚡ Zero Dependencies — Minimal bundle footprint (< 1 KB minified).
  • 🔄 Stale Closure Proof — Uses useRef internally so callbacks always read fresh state without re-attaching listeners.
  • 📦 Dual ESM & CommonJS — Works in Next.js (App & Pages Router), Vite, Remix, and React Native Web.

📥 Installation

# npm
npm install use-click-outside-react

# pnpm
pnpm add use-click-outside-react

# yarn
yarn add use-click-outside-react

# bun
bun add use-click-outside-react

🚀 Usage & Real-World Examples

1. Dropdown Menu

import React, { useState, useRef } from 'react';
import { useClickOutside } from 'use-click-outside-react';

export function Dropdown() {
  const [isOpen, setIsOpen] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);

  // Close dropdown whenever clicking outside:
  useClickOutside(menuRef, () => setIsOpen(false), { enabled: isOpen });

  return (
    <div className="relative">
      <button onClick={() => setIsOpen((prev) => !prev)}>Toggle Menu</button>
      {isOpen && (
        <div ref={menuRef} className="dropdown-panel">
          <ul>
            <li>Profile Settings</li>
            <li>Billing</li>
            <li>Logout</li>
          </ul>
        </div>
      )}
    </div>
  );
}

2. Modal Dialog with Escape Key

import React, { useRef } from 'react';
import { useClickOutside } from 'use-click-outside-react';

interface ModalProps {
  isOpen: boolean;
  onClose: () => void;
  children: React.ReactNode;
}

export function Modal({ isOpen, onClose, children }: ModalProps) {
  const dialogRef = useRef<HTMLDivElement>(null);

  // Closes when clicking backdrop OR pressing Escape key!
  useClickOutside(dialogRef, onClose, {
    enabled: isOpen,
    closeOnEscape: true,
  });

  if (!isOpen) return null;

  return (
    <div className="modal-backdrop">
      <div ref={dialogRef} className="modal-card">
        {children}
        <button onClick={onClose}>Close</button>
      </div>
    </div>
  );
}

3. Multi-Ref Handling (Trigger + Floating Popover)

When your trigger button and popover live in different parts of the DOM:

import React, { useState, useRef } from 'react';
import { useClickOutside } from 'use-click-outside-react';

export function Popover() {
  const [open, setOpen] = useState(false);
  const buttonRef = useRef<HTMLButtonElement>(null);
  const popoverRef = useRef<HTMLDivElement>(null);

  // Ignore clicks inside BOTH the button and the popover:
  useClickOutside([buttonRef, popoverRef], () => setOpen(false), {
    enabled: open,
    closeOnEscape: true,
  });

  return (
    <>
      <button ref={buttonRef} onClick={() => setOpen((o) => !o)}>
        Open Popover
      </button>
      {open && (
        <div ref={popoverRef} className="popover-content">
          <p>Helpful info tooltip!</p>
        </div>
      )}
    </>
  );
}

📖 API Reference

useClickOutside(refOrRefs, handler, options?)

| Parameter | Type | Default | Description | |---|---|---|---| | refOrRefs | RefObject \| RefObject[] | Required | Element ref or array of refs to treat as "inside" | | handler | (event) => void | Required | Callback when an outside interaction or escape occurs | | options | ClickOutsideOptions | {} | Configuration options |

ClickOutsideOptions:

| Option | Type | Default | Description | |---|---|---|---| | enabled | boolean | true | Enables or disables event listeners dynamically | | events | EventType[] | ['mousedown', 'touchstart'] | DOM pointer events to listen to | | closeOnEscape | boolean | false | If true, fires handler on Escape key press |


💖 Support the Project

If this hook made your UI components cleaner, please consider sponsoring:

👉 Sponsor @Piratha97 on GitHub Sponsors


📄 License

MIT © 2026 Pirapaakaran Pirathapan