All files / src/useTimeoutEffect useTimeoutEffect.ts

100% Statements 7/7
50% Branches 1/2
100% Functions 3/3
100% Lines 7/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28                                1x 1x 1x 1x 1x 1x   1x        
import { useEffect, useRef } from "react";
/**
 * This hook wraps `setTimeout` to trigger an effect of invoking the callback function when the timeout hits.
 * This will clear the timeout if the component containing the hook is unmounted.  Unlike `setTimeout` this
 * does not support call back functions that accept arguments.  This is due to the need to pass the
 * useEffect dependency list.
 *
 * This should only be used for short timeouts under 60 seconds.  Longer ones should use setTimeoutOn to
 * ensure that the timeout is going to be triggered correctly on Android.
 * @param callback - callback
 * @param ms - time before callback fires
 */
export function useTimeoutEffect(
  callback: () => void,
  ms: number | undefined
): void {
  const timeoutRef = useRef<ReturnType<typeof setTimeout>>();
  useEffect(() => {
    timeoutRef.current = setTimeout(callback, ms);
    return () => {
      Eif (timeoutRef.current !== undefined) {
        clearTimeout(timeoutRef.current);
      }
      timeoutRef.current = undefined;
    };
  }, [callback, ms]);
}