1.0.3 • Published 5 months ago

react-use-listener v1.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

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:

ParameterTypeDescription
elEventTargetTarget element or a React ref
eventstringEvent name (e.g., click, keydown)
callback(...args: any[]) => voidFunction to execute when event fires
optionsOptions (optional)Additional settings (see below)

Options:

OptionTypeDefaultDescription
debouncenumberundefinedDelay execution after inactivity (ms)
throttlenumberundefinedLimit execution rate (ms)
enabledbooleantrueEnable or disable the event listener
oncebooleanfalseRemove listener after the first execution
capturebooleanfalseUse event capturing instead of bubbling
passivebooleanfalseOptimize 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.