Skip to content
GaudiGaudi Design System home

Search documentation

Search every page, heading and paragraph.

useEventListener

Declarative DOM event listener with cleanup.

HooksInteraction@gaudi/design-system/hooks/interaction/use-event-listenerView in StorybookSource

Attaches a listener to window (default), document, an element or a ref, and removes it on unmount. The latest handler always runs without re-subscribing, and refs are re-read after every commit so the listener follows conditional elements.

Usage

import { useEventListener } from '@gaudi/design-system/hooks';
useEventListener('resize', () => setWidth(window.innerWidth));useEventListener('scroll', onScroll, panelRef, { passive: true });

Examples

Window events

Storybook

Document events

Storybook

An element through a ref

Storybook

API

4 options
1 return value

Accessibility

Keyboard listeners on window or document must not swallow keys that belong to focused controls; check event.target and event.defaultPrevented.

Notes

  • Mark scroll and touch listeners passive so they never delay scrolling.