|
1 |
| -import { useCallback } from 'react' |
| 1 | +import { useCallback, useMemo, useRef } from 'react' |
2 | 2 | import useTimeout from './useTimeout'
|
| 3 | +import useMounted from './useMounted' |
| 4 | + |
| 5 | +export interface UseDebouncedCallbackOptions { |
| 6 | + wait: number |
| 7 | + leading?: boolean |
| 8 | + trailing?: boolean |
| 9 | + maxWait?: number |
| 10 | +} |
3 | 11 |
|
4 | 12 | /**
|
5 | 13 | * Creates a debounced function that will invoke the input function after the
|
6 |
| - * specified delay. |
| 14 | + * specified wait. |
7 | 15 | *
|
8 | 16 | * @param fn a function that will be debounced
|
9 |
| - * @param delay The milliseconds delay before invoking the function |
| 17 | + * @param waitOrOptions a wait in milliseconds or a debounce configuration |
10 | 18 | */
|
11 | 19 | export default function useDebouncedCallback<
|
12 |
| - TCallback extends (...args: any[]) => any |
13 |
| ->(fn: TCallback, delay: number): (...args: Parameters<TCallback>) => void { |
| 20 | + TCallback extends (...args: any[]) => any, |
| 21 | +>( |
| 22 | + fn: TCallback, |
| 23 | + waitOrOptions: number | UseDebouncedCallbackOptions, |
| 24 | +): (...args: Parameters<TCallback>) => void { |
| 25 | + const lastCallTimeRef = useRef<number | null>(null) |
| 26 | + const lastInvokeTimeRef = useRef(0) |
| 27 | + |
| 28 | + const isTimerSetRef = useRef(false) |
| 29 | + const lastArgsRef = useRef<unknown[] | null>(null) |
| 30 | + |
| 31 | + const { |
| 32 | + wait, |
| 33 | + maxWait, |
| 34 | + leading = false, |
| 35 | + trailing = true, |
| 36 | + } = typeof waitOrOptions === 'number' |
| 37 | + ? ({ wait: waitOrOptions } as UseDebouncedCallbackOptions) |
| 38 | + : waitOrOptions |
| 39 | + |
14 | 40 | const timeout = useTimeout()
|
15 |
| - return useCallback( |
16 |
| - (...args: any[]) => { |
17 |
| - timeout.set(() => { |
18 |
| - fn(...args) |
19 |
| - }, delay) |
20 |
| - }, |
21 |
| - [fn, delay], |
22 |
| - ) |
| 41 | + |
| 42 | + return useMemo(() => { |
| 43 | + const hasMaxWait = !!maxWait |
| 44 | + |
| 45 | + function leadingEdge(time: number) { |
| 46 | + // Reset any `maxWait` timer. |
| 47 | + lastInvokeTimeRef.current = time |
| 48 | + |
| 49 | + // Start the timer for the trailing edge. |
| 50 | + isTimerSetRef.current = true |
| 51 | + timeout.set(timerExpired, wait) |
| 52 | + |
| 53 | + // Invoke the leading edge. |
| 54 | + if (leading) { |
| 55 | + invokeFunc(time) |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + function trailingEdge(time: number) { |
| 60 | + isTimerSetRef.current = false |
| 61 | + |
| 62 | + // Only invoke if we have `lastArgs` which means `func` has been |
| 63 | + // debounced at least once. |
| 64 | + if (trailing && lastArgsRef.current) { |
| 65 | + return invokeFunc(time) |
| 66 | + } |
| 67 | + |
| 68 | + lastArgsRef.current = null |
| 69 | + } |
| 70 | + |
| 71 | + function timerExpired() { |
| 72 | + var time = Date.now() |
| 73 | + |
| 74 | + if (shouldInvoke(time)) { |
| 75 | + return trailingEdge(time) |
| 76 | + } |
| 77 | + |
| 78 | + const timeSinceLastCall = time - (lastCallTimeRef.current ?? 0) |
| 79 | + const timeSinceLastInvoke = time - lastInvokeTimeRef.current |
| 80 | + const timeWaiting = wait - timeSinceLastCall |
| 81 | + |
| 82 | + // Restart the timer. |
| 83 | + timeout.set( |
| 84 | + timerExpired, |
| 85 | + hasMaxWait |
| 86 | + ? Math.min(timeWaiting, maxWait - timeSinceLastInvoke) |
| 87 | + : timeWaiting, |
| 88 | + ) |
| 89 | + } |
| 90 | + |
| 91 | + function invokeFunc(time: number) { |
| 92 | + const args = lastArgsRef.current ?? [] |
| 93 | + |
| 94 | + lastArgsRef.current = null |
| 95 | + lastInvokeTimeRef.current = time |
| 96 | + |
| 97 | + return fn(...args) |
| 98 | + } |
| 99 | + |
| 100 | + function shouldInvoke(time: number) { |
| 101 | + const timeSinceLastCall = time - (lastCallTimeRef.current ?? 0) |
| 102 | + const timeSinceLastInvoke = time - lastInvokeTimeRef.current |
| 103 | + |
| 104 | + // Either this is the first call, activity has stopped and we're at the |
| 105 | + // trailing edge, the system time has gone backwards and we're treating |
| 106 | + // it as the trailing edge, or we've hit the `maxWait` limit. |
| 107 | + return ( |
| 108 | + lastCallTimeRef.current === null || |
| 109 | + timeSinceLastCall >= wait || |
| 110 | + timeSinceLastCall < 0 || |
| 111 | + (hasMaxWait && timeSinceLastInvoke >= maxWait) |
| 112 | + ) |
| 113 | + } |
| 114 | + |
| 115 | + return (...args: any[]) => { |
| 116 | + const time = Date.now() |
| 117 | + const isInvoking = shouldInvoke(time) |
| 118 | + |
| 119 | + lastArgsRef.current = args |
| 120 | + lastCallTimeRef.current = time |
| 121 | + |
| 122 | + if (isInvoking) { |
| 123 | + if (!isTimerSetRef.current) { |
| 124 | + return leadingEdge(lastCallTimeRef.current) |
| 125 | + } |
| 126 | + |
| 127 | + if (hasMaxWait) { |
| 128 | + // Handle invocations in a tight loop. |
| 129 | + isTimerSetRef.current = true |
| 130 | + setTimeout(timerExpired, wait) |
| 131 | + return invokeFunc(lastCallTimeRef.current) |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + if (!isTimerSetRef.current) { |
| 136 | + isTimerSetRef.current = true |
| 137 | + setTimeout(timerExpired, wait) |
| 138 | + } |
| 139 | + } |
| 140 | + }, [fn, wait, maxWait, leading, trailing]) |
23 | 141 | }
|
0 commit comments