React useEventListener Hook: Type-Safe DOM Events (2026)
Here's a modal close-on-Escape that quietly does the wrong thing: function Modal ({ onClose }: { onClose : () => void }) { useEffect (() => { const onKey = ( e : KeyboardEvent ) => { if ( e . key === " Escape " ) onClose (); }; window . addEventListener ( " keydown " , onKey ); return () => window . removeEventListener ( " keydown " , onKey ); }, [ onClose ]); return < div role = "dialog" > … </ div >; } If the parent passes an inline onClose={() => setOpen(false)} — and it almost always does — onClose is a new function on every render, so this effect tears the listener down and adds a fresh one on every single render of the parent. Drop onClose from the deps to stop the churn and you get the other bug: the listener now holds the first render's onClose forever, and closing the modal calls a stale closure. You can't win this with a dependency array, because the two things you want are in direct conflict: subscribe once , but always run the newest handler . The fix is to separate them — register the listener on a stable identity, and call through a ref that's kept current. useEventListener from @reactuses/core is that split, packaged. This post covers what it actually does under the hood, the four ways to name a target, exactly what TypeScript infers for each one (this part surprises people), the options that don't retrigger, and the two gotchas worth knowing before you ship it. Quick Start npm install @reactuses/core import { useEventListener } from " @reactuses/core " ; function Modal ({ onClose }: { onClose : () => void }) { useEventListener ( " keydown " , ( e ) => { if ( e . key === " Escape " ) onClose (); }); return < div role = "dialog" > … </ div >; } That's the whole fix. No dependency array, no useCallback on the parent, no cleanup to remember. The listener is added to window once when the component mounts and removed when it unmounts; the arrow function you passed is re-created on every render and it doesn't matter, because the listener never re-registers