JAVASCRIPT

Generic Event Listener Hook

A versatile React hook for safely attaching and detaching event listeners to DOM elements or the window, ensuring proper cleanup and preventing memory leaks.

import { useEffect, useRef } from 'react';

const useEventListener = (eventName, handler, element = window) => {
  // Create a ref that stores handler
  const savedHandler = useRef();

  // Update ref.current value if handler changes.
  // This allows our effect to always get latest handler without re-running.
  useEffect(() => {
    savedHandler.current = handler;
  }, [handler]);

  useEffect(() => {
    // Make sure element supports addEventListener
    // On SSR, element won't be defined
    const isSupported = element && element.addEventListener;
    if (!isSupported) return;

    // Create event listener that calls handler function stored in ref
    const eventListener = (event) => savedHandler.current(event);

    // Add event listener
    element.addEventListener(eventName, eventListener);

    // Remove event listener on cleanup
    return () => {
      element.removeEventListener(eventName, eventListener);
    };
  }, [eventName, element]); // Re-run if eventName or element changes

  // No return value, just handles side effects
};

export default useEventListener;
How it works: This hook simplifies adding and cleaning up event listeners. It takes an `eventName`, a `handler` function, and an optional `element` (defaults to `window`). It uses `useRef` to store the latest `handler` function, ensuring that the `useEffect` doesn't need to re-run every time the `handler` changes. The `useEffect` attaches the event listener and returns a cleanup function to remove it when the component unmounts or 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