JavaScript Snippet

React useEventListener Hook

Difficulty: Medium

Manually attaching DOM event listeners inside useEffect is repetitive and easy to misuse: forgotten cleanups leak handlers, and stale callbacks see old state. The useEventListener hook centralises the pattern so consumers just declare which event they care about. This snippet covers the basic window listener, a target-aware variant that supports any element ref, and a typed signature that picks the right event payload.

Code Snippets
/

React useEventListener Hook

React useEventListener Hook

Manually attaching DOM event listeners inside useEffect is repetitive and easy to misuse: forgotten cleanups leak handlers, and stale callbacks see old state. The useEventListener hook centralises the pattern so consumers just declare which event they care about. This snippet covers the basic window listener, a target-aware variant that supports any element ref, and a typed signature that picks the right event payload.

JavaScript
Medium
3 snippets
react
hooks
code-template
js-event-loop

364 views

1

The hook stores the handler in a ref so the listener attached to the DOM stays referentially stable across renders, while still calling the latest handler. This avoids the subtle bug where a handler closure captures stale props. The typeof window guard makes the hook safe in SSR. Reach for this any time you need to listen on window (resize, scroll, online / offline, beforeunload) and want to keep your component bodies clean.