useEventListener
Attaches DOM event listeners with cleanup.
Attaches DOM event listeners with cleanup.
Import
import { useEventListener } from '@kamod-ch/hooks'Live demo
Basic demo
Attaches DOM event listeners with cleanup.
Browser-only demo
This demo starts after the page mounts in the browser.
import { useRef, useState } from 'preact/hooks'
import { useEventListener } from '@kamod-ch/hooks'
export default function UseEventListenerDemo() {
const ref = useRef<HTMLButtonElement>(null)
const [clicks, setClicks] = useState(0)
useEventListener('click', () => setClicks((value) => value + 1), { target: ref })
return (
<div>
<button ref={ref} type="button">Native listener target</button>
<p><strong>Captured clicks:</strong> {clicks}</p>
</div>
)
}
API
TypeScript signature
import type { BasicTarget } from '../utils/domTarget.js';
type noop = (...p: any) => void;
export type Target = BasicTarget<HTMLElement | Element | Window | Document>;
type TargetType = HTMLElement | Element | Window | Document;
type Options<T extends TargetType = TargetType> = {
target?: BasicTarget<T>;
capture?: boolean;
once?: boolean;
passive?: boolean;
enable?: boolean;
};
declare function useEventListener<K extends keyof HTMLElementEventMap>(eventName: K, handler: (ev: HTMLElementEventMap[K]) => void, options?: Options<HTMLElement>): void;
declare function useEventListener<K extends keyof ElementEventMap>(eventName: K, handler: (ev: ElementEventMap[K]) => void, options?: Options<Element>): void;
declare function useEventListener<K extends keyof DocumentEventMap>(eventName: K, handler: (ev: DocumentEventMap[K]) => void, options?: Options<Document>): void;
declare function useEventListener<K extends keyof WindowEventMap>(eventName: K, handler: (ev: WindowEventMap[K]) => void, options?: Options<Window>): void;
declare function useEventListener(eventName: string | string[], handler: (event: Event) => void, options?: Options<Window>): void;
declare function useEventListener(eventName: string | string[], handler: noop, options: Options): void;
export default useEventListener;
/SSR considerations
This hook touches browser APIs. Render it after mount or guard it with BrowserOnly in SSR and static builds.
Browser compatibility
Requires the corresponding browser API to exist in the current environment.