Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 | 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 62x 118x 62x 114x 114x 42x 72x 72x 72x 62x 37x 37x 37x 37x 37x 37x 62x 15x 15x 15x 15x 15x 15x 62x 62x 33x 33x 25x 8x 8x 62x 44x 44x 29x 15x 62x 62x 45x 45x 45x 62x 4x 4x 4x 4x 4x 4x 62x 7x 3x 4x 62x 8x 62x 70x 70x 70x 70x 70x 45x 45x 25x 25x 62x 53x 53x 9x 62x 53x 53x 53x 53x 53x 62x | import { useCallback, useEffect, useMemo, useRef } from "react";
/**
* Options for useDebounceCallback hook
*/
export interface UseDebounceCallbackOptions {
/**
* Maximum time the debounced function can be delayed
* @default undefined (no maximum)
*/
maxWait?: number;
/**
* Whether to invoke on the leading edge
* @default false
*/
leading?: boolean;
/**
* Whether to invoke on the trailing edge
* @default true
*/
trailing?: boolean;
}
/**
* Debounced function interface with control methods
*/
export interface DebouncedFunction<T extends (...args: any[]) => any> {
/**
* Call the debounced function
*/
(...args: Parameters<T>): ReturnType<T> | undefined;
/**
* Cancel any pending invocation
*/
cancel: () => void;
/**
* Immediately invoke any pending invocation
*/
flush: () => ReturnType<T> | undefined;
/**
* Check if there is a pending invocation
*/
pending: () => boolean;
}
/**
* Creates a debounced version of the provided callback function.
* The debounced function delays invoking the callback until after `delay` milliseconds
* have elapsed since the last time the debounced function was invoked.
*
* @template T - The type of the callback function
* @param callback - The function to debounce
* @param delay - The delay in milliseconds (default: 500ms)
* @param options - Additional options for controlling debounce behavior
* @returns A debounced version of the callback with cancel, flush, and pending methods
*
* @example
* ```tsx
* function SearchComponent() {
* const [results, setResults] = useState([]);
*
* const debouncedSearch = useDebounceCallback(
* async (query: string) => {
* const data = await searchAPI(query);
* setResults(data);
* },
* 500
* );
*
* return (
* <input
* type="text"
* onChange={(e) => debouncedSearch(e.target.value)}
* placeholder="Search..."
* />
* );
* }
* ```
*
* @example
* ```tsx
* // With leading edge invocation
* const debouncedFn = useDebounceCallback(callback, 300, { leading: true });
* ```
*
* @example
* ```tsx
* // With maximum wait time
* const debouncedFn = useDebounceCallback(callback, 500, { maxWait: 2000 });
*
* // Cancel pending invocation
* debouncedFn.cancel();
*
* // Immediately invoke pending invocation
* debouncedFn.flush();
*
* // Check if there's a pending invocation
* if (debouncedFn.pending()) {
* console.log('There is a pending call');
* }
* ```
*/
export function useDebounceCallback<T extends (...args: any[]) => any>(
callback: T,
delay: number = 500,
options: UseDebounceCallbackOptions = {}
): DebouncedFunction<T> {
// Parse options
const wait = delay || 0;
const leading = options.leading ?? false;
const trailing = options.trailing !== undefined ? options.trailing : true;
const maxing = "maxWait" in options;
const maxWait = maxing ? Math.max(options.maxWait || 0, wait) : undefined;
// Refs for mutable state
const callbackRef = useRef<T>(callback);
const timerIdRef = useRef<ReturnType<typeof setTimeout> | undefined>(
undefined
);
const lastCallTimeRef = useRef<number | undefined>(undefined);
const lastInvokeTimeRef = useRef<number>(0);
const lastArgsRef = useRef<Parameters<T> | undefined>(undefined);
const resultRef = useRef<ReturnType<T> | undefined>(undefined);
// Store options in refs
const waitRef = useRef(wait);
const leadingRef = useRef(leading);
const trailingRef = useRef(trailing);
const maxingRef = useRef(maxing);
const maxWaitRef = useRef(maxWait);
// Update callback ref on every render to always have the latest callback
callbackRef.current = callback;
// Update option refs when options change
waitRef.current = wait;
leadingRef.current = leading;
trailingRef.current = trailing;
maxingRef.current = maxing;
maxWaitRef.current = maxWait;
// Helper function to get current time
const now = useCallback(() => Date.now(), []);
// Helper function: shouldInvoke
const shouldInvoke = useCallback((time: number): boolean => {
const lastCallTime = lastCallTimeRef.current;
if (lastCallTime === undefined) {
return true; // First call
}
const timeSinceLastCall = time - lastCallTime;
const timeSinceLastInvoke = time - lastInvokeTimeRef.current;
return (
timeSinceLastCall >= waitRef.current ||
timeSinceLastCall < 0 || // System time went backwards
(maxingRef.current &&
timeSinceLastInvoke >= (maxWaitRef.current as number))
);
}, []);
// Helper function: invokeFunc
const invokeFunc = useCallback((time: number): ReturnType<T> | undefined => {
const args = lastArgsRef.current;
lastArgsRef.current = undefined;
lastInvokeTimeRef.current = time;
Eif (args !== undefined) {
resultRef.current = callbackRef.current(...args);
}
return resultRef.current;
}, []);
// Helper function: remainingWait
const remainingWait = useCallback((time: number): number => {
const lastCallTime = lastCallTimeRef.current;
Iif (lastCallTime === undefined) {
return waitRef.current;
}
const timeSinceLastCall = time - lastCallTime;
const timeSinceLastInvoke = time - lastInvokeTimeRef.current;
const timeWaiting = waitRef.current - timeSinceLastCall;
return maxingRef.current
? Math.min(
timeWaiting,
(maxWaitRef.current as number) - timeSinceLastInvoke
)
: timeWaiting;
}, []);
// Forward declare timerExpired for mutual recursion
const timerExpiredRef = useRef<() => void>(() => {});
// Helper function: trailingEdge
const trailingEdge = useCallback(
(time: number): ReturnType<T> | undefined => {
timerIdRef.current = undefined;
// Only invoke if trailing is true and we have args (meaning the function was called)
if (trailingRef.current && lastArgsRef.current !== undefined) {
return invokeFunc(time);
}
lastArgsRef.current = undefined;
return resultRef.current;
},
[invokeFunc]
);
// Helper function: timerExpired
const timerExpired = useCallback((): void => {
const time = now();
if (shouldInvoke(time)) {
trailingEdge(time);
} else {
// Restart the timer
timerIdRef.current = setTimeout(
timerExpiredRef.current,
remainingWait(time)
);
}
}, [now, shouldInvoke, trailingEdge, remainingWait]);
// Update the ref after timerExpired is defined
timerExpiredRef.current = timerExpired;
// Helper function: leadingEdge
const leadingEdge = useCallback(
(time: number): ReturnType<T> | undefined => {
// Reset any `maxWait` timer
lastInvokeTimeRef.current = time;
// Start the timer for the trailing edge
timerIdRef.current = setTimeout(timerExpiredRef.current, waitRef.current);
// Invoke the leading edge
return leadingRef.current ? invokeFunc(time) : resultRef.current;
},
[invokeFunc]
);
// Cancel function
const cancel = useCallback((): void => {
Eif (timerIdRef.current !== undefined) {
clearTimeout(timerIdRef.current);
}
lastInvokeTimeRef.current = 0;
lastArgsRef.current = undefined;
lastCallTimeRef.current = undefined;
timerIdRef.current = undefined;
}, []);
// Flush function
const flush = useCallback((): ReturnType<T> | undefined => {
if (timerIdRef.current === undefined) {
return resultRef.current;
}
return trailingEdge(now());
}, [now, trailingEdge]);
// Pending function
const pending = useCallback((): boolean => {
return timerIdRef.current !== undefined;
}, []);
// Main debounced function
const debounced = useCallback(
(...args: Parameters<T>): ReturnType<T> | undefined => {
const time = now();
const isInvoking = shouldInvoke(time);
lastArgsRef.current = args;
lastCallTimeRef.current = time;
if (isInvoking) {
Eif (timerIdRef.current === undefined) {
return leadingEdge(time);
}
if (maxingRef.current) {
// Handle invocations in a tight loop
clearTimeout(timerIdRef.current);
timerIdRef.current = setTimeout(
timerExpiredRef.current,
waitRef.current
);
// Only invoke if at least one edge is enabled (matches lodash behavior)
if (leadingRef.current || trailingRef.current) {
return invokeFunc(time);
}
}
}
Iif (timerIdRef.current === undefined) {
timerIdRef.current = setTimeout(
timerExpiredRef.current,
waitRef.current
);
}
return resultRef.current;
},
[now, shouldInvoke, leadingEdge, invokeFunc]
);
// Cleanup on unmount
useEffect(() => {
return () => {
if (timerIdRef.current !== undefined) {
clearTimeout(timerIdRef.current);
}
};
}, []);
// Create the debounced function with attached methods
const debouncedWithMethods = useMemo(() => {
const fn = debounced as DebouncedFunction<T>;
fn.cancel = cancel;
fn.flush = flush;
fn.pending = pending;
return fn;
}, [debounced, cancel, flush, pending]);
return debouncedWithMethods;
}
|