useEventListener
A hook that provides a declarative way to attach event listeners to DOM elements. Perfect for handling browser events, custom events, and global event listeners.
Parameters
eventName
:string
- Name of the event to listen forcallback
:EventListener
- Function to handle the eventelement?
:HTMLElement | Window | Document | null
- Target element (defaults to window)
Usage
import { useEventListener } from '@rhinolabs/react-hooks';
function KeyLogger() {
const handleKeyPress = (event: KeyboardEvent) => {
console.log(`Key pressed: ${event.key}`);
};
useEventListener('keypress', handleKeyPress);
return <div>Press any key (check console)</div>;
}
Advanced Usage with Element Target
import { useEventListener } from '@rhinolabs/react-hooks';
import { useRef } from 'react';
function ClickTracker() {
const buttonRef = useRef<HTMLButtonElement>(null);
const handleClick = (event: MouseEvent) => {
console.log('Button clicked at:', {
x: event.clientX,
y: event.clientY
});
};
useEventListener('click', handleClick, buttonRef.current);
return (
<button ref={buttonRef}>
Click me to track coordinates
</button>
);
}
Notes
- Supports all DOM event types
- Handles callback updates safely
- Automatic cleanup on unmount
- Works with any DOM element
- Defaults to window target
- Type-safe event handling
- Memoizes event listener
- Prevents memory leaks
Last updated on