JAVASCRIPT

Attach Global or Element-Specific Event Listeners with useEventListener

A flexible React hook, `useEventListener`, for cleanly attaching and detaching event listeners to the window, document, or a specific DOM element referenced by a ref.

import { useEffect, useRef } from 'react';

const 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]);
};

export default useEventListener;
How it works: The `useEventListener` hook simplifies managing event listeners in React. It safely attaches an event listener (e.g., 'click', 'keydown') to a specified `element` (defaults to `window`) and automatically cleans it up when the component unmounts or dependencies change, preventing memory leaks and ensuring correct behavior. It's a foundational utility for many interactive components.

Need help integrating this into your project?

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

Hire DigitalCodeLabs