JAVASCRIPT
Attach Global Event Listeners Safely with useEventListener
Create a versatile useEventListener React hook to easily attach and detach event listeners to the window, document, or a specific DOM element, ensuring proper cleanup.
import { useEffect, useRef } from 'react';
function useEventListener(eventType, handler, element = window) {
const savedHandler = useRef();
useEffect(() => {
savedHandler.current = handler;
}, [handler]);
useEffect(() => {
const isSupported = element && element.addEventListener;
if (!isSupported) return;
const eventListener = (event) => savedHandler.current(event);
element.addEventListener(eventType, eventListener);
return () => {
element.removeEventListener(eventType, eventListener);
};
}, [eventType, element]);
}
export default useEventListener;
How it works: The useEventListener hook simplifies attaching event listeners to the window, document, or a specific DOM element (passed via ref or direct reference). It ensures that the event listener is correctly added when the component mounts and automatically removed when it unmounts, preventing memory leaks and ensuring that the latest event handler is always used. This makes managing global or element-specific events much cleaner and safer in React applications.