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.
