1.0.11 ⢠Published 8 months ago
@rsxt/react-listener v1.0.11
React Listener Hook
A lightweight and flexible React hook for handling event listeners with debounce, delay, and CSS selectors support.
š¦ Installation
yarn add react-listener
# or
npm install react-listenerš Usage
Basic Example
import { useListener } from "react-listener";
function App() {
  useListener(window, "resize", () => {
    console.log("Window resized!");
  });
  return <div>Resize the window to see logs in the console.</div>;
}Debounce Example
useListener(
  window,
  "scroll",
  () => {
    console.log("Scrolled!");
  },
  { debounce: 500 }
);Using a Ref
import { useRef } from "react";
import { useListener } from "react-listener";
function ClickCounter() {
  const btnRef = useRef(null);
  const [count, setCount] = useState(0);
  useListener(btnRef, "click", () => setCount((prev) => prev + 1));
  return <button ref={btnRef}>Clicked {count} times</button>;
}š Features
ā
 Supports Multiple Events (click, keydown, etc.)
ā
 Debounce and Delay Support
ā
 Attach Listeners to Refs or Window/Document
ā
 CSS Selector Support (for dynamically added elements)
ā
 Automatic Cleanup on Unmount
š License
This project is licensed under the MIT License.