← Back to all snippets
JAVASCRIPT

Centralize Global Event Listener Management with `useEventListener`

Implement a flexible `useEventListener` React hook to easily attach and clean up event listeners to the window, document, or any DOM element, simplifying event handling.

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 ScrollTracker() {
  const [scrollPos, setScrollPos] = useState(0);

  useEventListener('scroll', () => {
    setScrollPos(window.scrollY);
  });

  return (
    <div>
      <p>Scroll Y: {scrollPos}</p>
      <div style={{ height: '200vh' }}>Scroll down to see the effect.</div>
    </div>
  );
}
*/
How it works: The `useEventListener` hook simplifies attaching and cleaning up event listeners. It accepts an event name, a handler function, and an optional target element (defaulting to `window`). It uses a `useRef` to keep the `handler` stable across renders, preventing unnecessary re-subscriptions to the event. The `useEffect` hook ensures the event listener is added when the component mounts and automatically removed when it unmounts, preventing memory leaks and ensuring proper resource management.

Need help integrating this into your project?

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

Hire DigitalCodeLabs