JAVASCRIPT

Reusable useEventListener Hook

Create a custom React hook `useEventListener` to easily attach and clean up event listeners to the window, document, or a specific DOM element, ensuring no 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]);
}

// Example Usage in a component:
// function MyComponent() {
//   const [coords, setCoords] = useState({ x: 0, y: 0 });
//   const handleMouseMove = useCallback(({ clientX, clientY }) => {
//     setCoords({ x: clientX, y: clientY });
//   }, []);
//
//   useEventListener('mousemove', handleMouseMove);
//
//   return (
//     <div>
//       Mouse Coords: ({coords.x}, {coords.y})
//     </div>
//   );
// }
How it works: This `useEventListener` hook provides a declarative way to add and remove event listeners. It uses a `useRef` to keep a stable reference to the `handler` function, preventing unnecessary re-attaching of the listener when the handler changes. The `useEffect` hook handles adding the listener and ensures proper cleanup on unmount or when `eventType` or `element` dependencies change, preventing memory leaks.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs