import { useEffect, useMemo, useRef } from 'react'

export function useDebouncedCallback<T extends (...args: never[]) => void>(fn: T, delay: number): T {
  const ref = useRef(fn)
  useEffect(() => {
    ref.current = fn
  })
  return useMemo(() => {
    let timer: ReturnType<typeof setTimeout> | undefined
    return ((...args: Parameters<T>) => {
      if (timer) clearTimeout(timer)
      timer = setTimeout(() => ref.current(...args), delay)
    }) as T
  }, [delay])
}
