JAVASCRIPT

React useEventListener Hook for Clean Event Management

Learn to create a versatile useEventListener custom hook in React for cleanly attaching and detaching event listeners to DOM elements.

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]); // Re-run if eventName or element changes

  // No return value needed, this hook is for side effects
}

// Usage example:
// function MyComponent() {
//   const [coords, setCoords] = useState({ x: 0, y: 0 });
//   const handleMouseMove = ({ clientX, clientY }) => {
//     setCoords({ x: clientX, y: clientY });
//   };
//
//   useEventListener('mousemove', handleMouseMove);
//
//   return (
//     <div>
//       <p>Mouse X: {coords.x}</p>
//       <p>Mouse Y: {coords.y}</p>
//     </div>
//   );
// }
How it works: The `useEventListener` hook simplifies the process of adding and removing event listeners. It takes an event name, a handler function, and an optional target element (defaulting to `window`). It uses `useRef` to store the latest handler to prevent unnecessary re-renders of the effect, and `useEffect` to attach the listener on mount and clean it up on unmount or when `eventName` or `element` dependencies change.

Need help integrating this into your project?

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

Hire DigitalCodeLabs