import { useCallback, useInsertionEffect, useRef } from 'react';

/**
 * Polyfill for React's useEffectEvent hook.
 *
 * @see https://react.dev/reference/react/useEffectEvent
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useEffectEvent<T extends (...args: any[]) => any>(fn: T): T {
  const ref = useRef(fn);
  useInsertionEffect(() => {
    ref.current = fn;
  }, [fn]);

  return useCallback((...args: Parameters<T>) => ref.current(...args), []) as T;
}
