useEventListener Hook Solves React's Stale Closure and Re-registration Problem
A common React pattern for DOM event listeners — such as closing a modal on Escape — silently causes bugs when handler functions are recreated on every render, leading to either constant listener re-registration or stale closures. The core conflict is that a standard useEffect dependency array cannot simultaneously subscribe once and always call the latest handler. The open-source hook useEventListener from @reactuses/core resolves this by storing the handler in a ref via useLatest, so the DOM listener is registered only once while always invoking the most current callback. The target defaults to window but supports multiple ways to specify a DOM element, and options are deep-compared to avoid unnecessary re-subscriptions. The approach eliminates the need for useCallback on parent components, manual cleanup, or dependency array tuning for event listener scenarios.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.

Discussion (0)
Log in to join the discussion and vote.
Log in