Demo CodeSandbox
A powerful and flexible React hook for attaching and managing event listeners on DOM elements with built-in support for debouncing and throttling.
- ✅ 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
npm install react-use-listener
or
yarn add react-use-listener
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>;
}
import { useListener } from "react-use-listener";
function SearchBox() {
useListener(
window,
"resize",
() => {
console.log("Resized!");
},
{ throttle: 200 }
);
return <input type="text" placeholder="Search..." />;
}
useListener(el, event, callback, options);
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) |
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()
|
- 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 likescroll
andresize
. -
Prefer
debounce
for user input events likekeyup
andsearch
.
- Clone the repository:
git clone https://github.com/md-adil/use-listener.git
- Install dependencies:
cd use-listener npm install
- Run tests:
npm test
MIT License. See LICENSE for details.