react-event-listener is a lightweight React component that offers a declarative way to manage global DOM event listeners, specifically targeting `window` and `document`. It leverages React's component lifecycle to automatically bind and unbind events, preventing common memory leaks and simplifying event management for global scopes. The current stable version is `0.6.7`, and releases are infrequent, primarily focused on maintenance and compatibility updates rather than new features, indicating a mature and stable library. A key differentiator is its `withOptions` utility, allowing developers to configure standard `addEventListener` options like `passive` and `capture` declaratively. It aims to solve the problem of imperatively adding and removing global event listeners by integrating them seamlessly into the React component tree.
npm install react-event-listenerVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to use EventListener to bind to global 'window' resize and scroll events, and 'document' keydown events, including the use of `withOptions` for event configuration.
Define event handler methods as class properties (as shown in the quickstart) or use `useCallback` hook in functional components to ensure stable function references across renders, preventing unnecessary re-bindings and performance issues.
Conditionally render the `EventListener` component only on the client-side, or ensure the `target` prop is a string ('window', 'document') which the library handles gracefully on the server, by doing nothing.For testing global event listeners, use native DOM event dispatching methods such as `document.dispatchEvent(new Event('event-name'))` or `window.dispatchEvent(new Event('event-name'))` to accurately simulate global events.