xref: /expo/home/utils/useThrottle.ts (revision 94dbd83c)
1import React from 'react';
2
3export function useThrottle<T>(value: T, interval = 500): T {
4  const [throttledValue, setThrottledValue] = React.useState<T>(value);
5  const lastExecuted = React.useRef<number>(Date.now());
6
7  React.useEffect(() => {
8    if (Date.now() >= lastExecuted.current + interval) {
9      lastExecuted.current = Date.now();
10      setThrottledValue(value);
11      return () => {};
12    } else {
13      const timerId = setTimeout(() => {
14        lastExecuted.current = Date.now();
15        setThrottledValue(value);
16      }, interval);
17
18      return () => clearTimeout(timerId);
19    }
20  }, [value, interval]);
21
22  return throttledValue;
23}
24