aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-timeout/use-timeout.ts
blob: 4d1ed477e33f419a052f41396cc7e168fa523780 (plain)
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
29
import { type MutableRefObject, useEffect, useRef } from 'react';

export type UseTimeoutCallback = () => void;

export type UseTimeoutId = string | number | NodeJS.Timeout | undefined;

/**
 * React hook to schedule the execution of a one-time callback after delay.
 *
 * @param {UseTimeoutCallback} callback - The callback to schedule.
 * @param {number} [delay] - A delay in ms.
 * @returns {MutableRefObject<UseTimeoutId>} The timeout id.
 */
export const useTimeout = (
  callback: UseTimeoutCallback,
  delay = 0
): MutableRefObject<UseTimeoutId> => {
  const idRef = useRef<UseTimeoutId>(undefined);

  useEffect(() => {
    idRef.current = setTimeout(() => callback(), delay);

    return () => {
      clearTimeout(idRef.current);
    };
  }, [callback, delay]);

  return idRef;
};