import { useEffect, useRef } from "react";
import useIsomorphicLayoutEffect from "./useIsomorphicLayoutEffect"; // MediaQueryList Event based useEventListener interface

function useEventListener(eventName, handler, element, options) {
  // Create a ref that stores handler
  var savedHandler = useRef(handler);
  useIsomorphicLayoutEffect(function () {
    savedHandler.current = handler;
  }, [handler]);
  useEffect(function () {
    var _element$current;

    // Define the listening target
    var targetElement = (_element$current = element === null || element === void 0 ? void 0 : element.current) !== null && _element$current !== void 0 ? _element$current : window;
    if (!(targetElement && targetElement.addEventListener)) return; // Create event listener that calls handler function stored in ref

    var listener = function listener(event) {
      return savedHandler.current(event);
    };

    targetElement.addEventListener(eventName, listener, options); // Remove event listener on cleanup

    return function () {
      targetElement.removeEventListener(eventName, listener, options);
    };
  }, [eventName, element, options]);
}

export default useEventListener;