import { useEffect, useRef, useState } from 'react';
import throttle from 'lodash/throttle';

/**
 * Use this hook for debounced parameters, for example for useQuery
 * @param value
 * @param delay
 * @return debounced value
 * @see https://github.com/uidotdev/usehooks/blob/90fbbb4cc085e74e50c36a62a5759a40c62bb98e/index.js#L239-L253
 */
export function useThrottleValue(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);
  const onChangeThrottled = useRef(throttle(setDebouncedValue, delay));
  useEffect(() => {
    onChangeThrottled.current?.cancel?.();
    onChangeThrottled.current = throttle(setDebouncedValue, delay);
    return () => onChangeThrottled.current?.cancel?.();
  }, [delay]);
  useEffect(() => {
    onChangeThrottled.current?.(value);
  }, [value]);
  return debouncedValue;
}