JAVASCRIPT

Building a useEventListener Custom Hook for React

Simplify event listener management in React components with `useEventListener`. Attach and clean up event listeners efficiently for any DOM element or window.

import { useRef, useEffect } 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 MyComponent() {
  const clickHandler = () => console.log('Window clicked!');
  useEventListener('click', clickHandler);

  return <div>Click anywhere on the window.</div>;
}
How it works: The `useEventListener` hook abstracts the process of adding and removing event listeners. It uses `useRef` to maintain a stable reference to the `handler` function, preventing unnecessary re-subscriptions. The main `useEffect` handles attaching the listener when the component mounts and cleaning it up when it unmounts, ensuring no memory leaks and proper lifecycle management.

Need help integrating this into your project?

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

Hire DigitalCodeLabs