JAVASCRIPT
React useEventListener Hook for Global Event Management
Efficiently attach and detach event listeners to the window, document, or specific DOM elements using a custom `useEventListener` React hook, ensuring proper cleanup.
import { useEffect, useRef } from 'react';
function useEventListener(eventName, 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(eventName, eventListener);
return () => {
element.removeEventListener(eventName, eventListener);
};
}, [eventName, element]);
}
// Example Usage:
/*
function MouseLogger() {
const handleMouseMove = (event) => {
console.log(`Mouse X: ${event.clientX}, Y: ${event.clientY}`);
};
useEventListener('mousemove', handleMouseMove);
return <div>Move your mouse around! Check console.</div>;
}
*/
How it works: The `useEventListener` hook simplifies the process of adding and removing event listeners in React. It safely attaches an event listener to a specified element (defaults to `window`) and ensures that the listener is properly cleaned up when the component unmounts or dependencies change. It uses `useRef` to store the latest `handler` callback, preventing stale closures and unnecessary re-creations of the event listener, thus optimizing performance and preventing memory leaks.