import { useEffect, useRef } from 'react';

export default function useDismount(
  callback: () => void,
  timeout: number = 100
): void {
  const dismountTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
  useEffect(() => {
    if (dismountTimeout.current) {
      clearTimeout(dismountTimeout.current);
    }
    // if the component using this dismounts and stays dismounted, run the callback
    // if some other change or lifecycle mishap causes this useEffect to rerun, or causes the same instance of the wrapping component to rapidly dismount and remount, do not run the callback
    return () => {
      dismountTimeout.current = setTimeout(() => {
        callback();
      }, timeout);
    };
  }, [callback, timeout]);
}
