-
Notifications
You must be signed in to change notification settings - Fork 0
/
use-throttle.ts
46 lines (38 loc) · 1.15 KB
/
use-throttle.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
36
37
38
39
40
41
42
43
44
45
46
import { useEffect, useRef, useState } from 'react';
import { useUpdateEffect } from './use-update-effect';
import { noop } from './utils';
/**
* Get throttled value.
*
* •
*
* @param value Value to be throttled.
* @param {number} delay Delay in milliseconds.
* @param {Function} callbackFn Callback function after throttled.
*/
export function useThrottle<T>(value: T, delay: number, callbackFn: (value: T) => void = noop): T {
const [throttledValue, setThrottledValue] = useState(value);
const timeout = useRef<NodeJS.Timeout>();
const nextValue = useRef(value);
const callbackFnRef = useRef(callbackFn);
useEffect(() => {
callbackFnRef.current = callbackFn;
}, [callbackFn]);
useUpdateEffect(() => {
nextValue.current = value;
if (!timeout.current) {
timeout.current = setTimeout(() => {
setThrottledValue(nextValue.current);
callbackFnRef.current(nextValue.current);
timeout.current = undefined;
}, delay);
}
}, [value, delay]);
useEffect(() => {
return () => {
clearTimeout(timeout.current);
timeout.current = undefined;
};
}, []);
return throttledValue;
}