useEventListener hook
Attach a DOM event listener once and keep the handler current, so a changing callback never detaches the listener.
react/hooks1 min read
- #react
- #hooks
- #events
Subscribes to a DOM event once and keeps the handler current through a ref, so a new callback identity never detaches and reattaches the listener.
Overview
An inline handler in a useEffect dependency array re-subscribes on every render. A ref holds the handler instead, which separates how long the subscription lives from which function it calls.
Implementation
typescript
Usage example
tsx
Related entries
- Accessible command menu. Uses a global key listener for its
Cmd+Ktrigger. - useMediaQuery hook. The same subscription shape over a media query list.
Related entries
react1 min
useMediaQuery hook
Subscribe to a CSS media query from React, without a resize listener or a layout read.
react1 min
useLocalStorage hook
A state hook that mirrors its value into localStorage, with safe hydration and cross-tab synchronization.
react1 min
useIntersectionObserver hook
Track element visibility for lazy loading, infinite scroll and scroll-spy navigation.