File size: 801 Bytes
75fefa7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, useRef
} from 'react';

const DEFAULT_CONFIG = { timeout: 0 };

export function useDebouncedCallback<T extends (...args: any[]) => any>(
  callback: T,
  config: number | { timeout?: number }
): T {
  const timeoutRef = useRef(0);
  const callbackRef = useRef(callback);
  callbackRef.current = callback;

  const currentConfig = typeof config === 'object' ? {
    ...DEFAULT_CONFIG,
    ...config
  } : {
    ...DEFAULT_CONFIG,
    timeout: config
  };

  return useCallback((...args: Parameters<T>) => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }

    timeoutRef.current = window.setTimeout(() => {
      callbackRef.current(...args);
    }, currentConfig.timeout);
  }, [currentConfig.timeout]) as T;
}

export default useDebouncedCallback;