react-use-listener
TypeScript icon, indicating that this package has built-in type declarations

1.0.3 • Public • Published

Demo CodeSandbox

useListener

A powerful and flexible React hook for attaching and managing event listeners on DOM elements with built-in support for debouncing and throttling.

🚀 Features

  • Declarative event listener management
  • Supports debouncing and throttling
  • Works with refs and direct DOM elements
  • Automatic cleanup to prevent memory leaks
  • Flexible options: capture, passive, once

📦 Installation

npm install react-use-listener

or

yarn add react-use-listener

🔧 Usage

Basic Example

import { useRef } from "react";
import { useListener } from "react-use-listener";

function App() {
  const buttonRef = useRef<HTMLButtonElement>(null);

  useListener(buttonRef, "click", () => {
    console.log("Button clicked!");
  });

  return <button ref={buttonRef}>Click Me</button>;
}

Using Debounce and Throttle

import { useListener } from "react-use-listener";

function SearchBox() {
  useListener(
    window,
    "resize",
    () => {
      console.log("Resized!");
    },
    { throttle: 200 }
  );

  return <input type="text" placeholder="Search..." />;
}

📜 API Reference

useListener

useListener(el, event, callback, options);

Parameters:

Parameter Type Description
el EventTarget Target element or a React ref
event string Event name (e.g., click, keydown)
callback (...args: any[]) => void Function to execute when event fires
options Options (optional) Additional settings (see below)

Options:

Option Type Default Description
debounce number undefined Delay execution after inactivity (ms)
throttle number undefined Limit execution rate (ms)
enabled boolean true Enable or disable the event listener
once boolean false Remove listener after the first execution
capture boolean false Use event capturing instead of bubbling
passive boolean false Optimize performance by preventing preventDefault()

🎯 Best Practices

  • Use refs for dynamically created elements to ensure proper listener management.
  • Use enabled: false when the listener is not needed to avoid unnecessary event bindings.
  • Prefer throttle for performance-sensitive events like scroll and resize.
  • Prefer debounce for user input events like keyup and search.

🛠 Contributing

  1. Clone the repository:
    git clone https://github.com/md-adil/use-listener.git
  2. Install dependencies:
    cd use-listener
    npm install
  3. Run tests:
    npm test

📄 License

MIT License. See LICENSE for details.

Package Sidebar

Install

npm i react-use-listener

Weekly Downloads

359

Version

1.0.3

License

MIT

Unpacked Size

7.61 kB

Total Files

10

Last publish

Collaborators

  • adil.sudo