JAVASCRIPT
Dynamic Event Listener Management with useEventListener Hook
A custom React hook to simplify adding and removing event listeners dynamically, ensuring proper cleanup on component unmount to prevent memory leaks.
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]);
}
How it works: This `useEventListener` hook allows you to easily attach event listeners to the window or any specified DOM element. It uses `useRef` to keep track of the latest handler function and `useEffect` to add the listener when the component mounts and remove it when the component unmounts, preventing memory leaks and ensuring efficient resource management.