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

// Polyfill for React's `useEffectEvent` (canary). The returned function has a
// stable identity but always sees the latest closure — exactly what
// `useEffectEvent` provides. Stable enough that we use it everywhere we'd
// otherwise reach for a ref + .current dance inside an effect.
//
// Replace with `useEffectEvent` once it ships in stable React. Call sites
// don't need to change.
export function useEvent<TArgs extends unknown[], TReturn>(
  fn: (...args: TArgs) => TReturn,
): (...args: TArgs) => TReturn {
  const ref = useRef(fn);
  useLayoutEffect(() => {
    ref.current = fn;
  });
  return useCallback((...args: TArgs) => ref.current(...args), []);
}
