-
Notifications
You must be signed in to change notification settings - Fork 0
/
use-timeout.ts
35 lines (28 loc) · 882 Bytes
/
use-timeout.ts
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
30
31
32
33
34
35
import { useCallback, useEffect, useRef } from 'react';
/**
* Simplify the interaction with timeout in React
* @param {() => void} effectCallback Imperative function
* @param {number} delay timeout delay
*/
export function useTimeout(effectCallback: () => void, delay: number) {
const callbackRef = useRef(effectCallback);
const timeoutRef = useRef<NodeJS.Timeout>();
useEffect(() => {
callbackRef.current = effectCallback;
}, [effectCallback]);
const set = useCallback(() => {
timeoutRef.current = setTimeout(() => callbackRef.current(), delay);
}, [delay]);
const clear = useCallback(() => {
timeoutRef.current && clearTimeout(timeoutRef.current);
}, []);
useEffect(() => {
set();
return clear;
}, [delay, set, clear]);
const reset = useCallback(() => {
clear();
set();
}, [clear, set]);
return { reset, clear };
}