File size: 1,278 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import {
  useEffect, useRef
} from 'react';

const DEFAULT_CONFIG = {
  timeout: 0,
  ignoreInitialCall: true
};

export function useDebouncedEffect(
  callback: () => (void | (() => void)),
  config: number | {
    timeout?: number;
    ignoreInitialCall?: boolean;
  },
  deps: any[] = []
): void {
  let currentConfig;

  if (typeof config === 'object') {
    currentConfig = {
      ...DEFAULT_CONFIG,
      ...config
    };
  } else {
    currentConfig = {
      ...DEFAULT_CONFIG,
      timeout: config
    };
  }
  const {
    timeout, ignoreInitialCall
  } = currentConfig;

  const data = useRef<{ firstTime: boolean }>({ firstTime: true });

  useEffect(() => {
    const { firstTime } = data.current;

    if (firstTime && ignoreInitialCall) {
      data.current.firstTime = false;

      return;
    }

    let clearFunc: (() => void) | undefined;

    const handler = setTimeout(() => {
      clearFunc = callback() ?? undefined;
    }, timeout);

    return () => {
      clearTimeout(handler);

      if (clearFunc && typeof clearFunc === 'function') {
        clearFunc();
      }
    };
  }, [
    callback,
    ignoreInitialCall,
    timeout,
    // eslint-disable-next-line react-hooks/exhaustive-deps
    ...deps
  ]);
}

export default useDebouncedEffect;