import { useCallback, useEffect, useRef, useState } from 'react';

export default function useForceReload(delay: number = 300): [number, () => void] {
  const [force, setForce] = useState<number>(1);
  const timeoutRef = useRef<number | undefined>(undefined);

  const reload = useCallback(() => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }
    timeoutRef.current = window.setTimeout(() => {
      setForce((prev) => prev + 1);
    }, delay);
  }, [delay]);

  useEffect(
    () => () => {
      if (timeoutRef.current !== undefined) {
        clearTimeout(timeoutRef.current);
      }
    },
    [],
  );

  return [force, reload];
}
