useEventListener
A React hook that provides a declarative way to add event listeners to DOM elements or window, with proper cleanup and TypeScript support for all DOM events.
Demo
1. Keyboard Events
2. Mouse Events
3. Scroll Events
Installation
npm install @thibault.sh/hooks
Usage
import { useEventListener } from "@thibault.sh/hooks";
function KeyPressTracker() {
const [keys, setKeys] = useState<string[]>([]);
useEventListener("keydown", (event) => {
setKeys(prev => [...prev, event.key].slice(-5));
});
return (
<div>
<h3>Last 5 keys pressed:</h3>
<div>{keys.join(", ")}</div>
</div>
);
}
function ClickTracker() {
const buttonRef = useRef<HTMLButtonElement>(null);
const [clicks, setClicks] = useState(0);
useEventListener(
"click",
() => setClicks(c => c + 1),
buttonRef
);
return (
<button ref={buttonRef}>
Clicked {clicks} times
</button>
);
}
API Reference
Parameters
eventName
The name of the DOM event to listen for (e.g., "click", "keydown", "scroll"). TypeScript will ensure you can only pass valid event names.
keyof EventMap
handler
The event handler function that will be called when the event occurs. The function receives the event object with the correct type based on the event name.
(event: EventMap[K]) => void
element
Optional ref to the target DOM element. If not provided, the event listener will be added to the window object. Must be a React ref created with useRef.
RefObject<HTMLElement> | null
options
Optional addEventListener options or boolean for useCapture. These are passed directly to the native addEventListener method.
boolean | AddEventListenerOptions
Features
Type Safety
Full TypeScript support for event names and handler types, ensuring you can only add listeners for valid DOM events with correct handler signatures.
Automatic Cleanup
Event listeners are automatically removed when the component unmounts or when dependencies change, preventing memory leaks and stale handlers.
Flexible Target
Works with both window events and element-specific events using React refs, providing a consistent API for all event types.
Native Options Support
Supports all native addEventListener options like capture, passive, and once, giving you full control over event behavior.
Common Use Cases
Listen for keyboard events to implement hotkeys and keyboard shortcuts that work globally or within specific components.
Combine with refs to detect clicks outside a specific element, useful for implementing dropdown menus and modal dialogs.
Track scroll position to implement infinite scrolling, scroll-to-top buttons, or scroll-based animations and transitions.
Listen for window resize events to create responsive layouts and update UI elements based on viewport dimensions.