Documentation Index
Fetch the complete documentation index at: https://mintlify.com/rijvi-mahmud/shaddy/llms.txt
Use this file to discover all available pages before exploring further.
useEventListener is a React hook that attaches an event listener to a DOM element — window, document, any HTMLElement, or any SVGElement — and automatically removes it when the component unmounts or when the event name, element, or options change. It is fully generic: TypeScript infers the correct event type from the element and event name combination, so your handler receives a properly typed event object with no manual casting. It also supports event delegation via a selector option, letting a single listener handle events from many child elements efficiently.
Installation
Signature
Parameters
The name of the DOM event to listen for (e.g.
'click', 'keydown', 'resize', 'scroll'). TypeScript constrains the valid values to the event map of the target element type, giving you autocomplete for event names.The callback to invoke when the event fires. The
event parameter is automatically typed to match the element–event combination (e.g. MouseEvent for a click on an HTMLElement, KeyboardEvent for keydown). When using event delegation, a second delegateTarget argument contains the matched element.The target element to attach the listener to. Defaults to
window when omitted or null. Pass a ref’s .current value to attach to a specific DOM node.Standard
addEventListener options (capture, once, passive) plus an optional selector string for event delegation. When selector is provided, the handler is only called when the event target (or one of its ancestors) matches the CSS selector.Return Value
useEventListener returns void. Its effect is the side effect of attaching the listener.
Usage
Window Resize
Keyboard Events on Document
Specific Element via Ref
Event Delegation
Passive Scroll Listener
Notes
- The handler is stored in a ref so updating it between renders never triggers a listener re-attach. You will always get the freshest callback without resetting the event subscription.
- Cleanup is fully automatic — the listener is removed when the component unmounts or when
eventName,element, oroptionschange. - If
elementis invalid or does not supportaddEventListener, the hook logs a warning and skips attachment gracefully. - When using the
selectoroption for event delegation, the hook callsElement.closest(selector)on the event target and only fires your handler when a match is found. - The
selectorproperty is stripped from the options before being passed toaddEventListener, so it never causes browser errors.