MCPcopy Create free account
hub / github.com/dailydotdev/apps / useDebounceFn

Function useDebounceFn

packages/shared/src/hooks/useDebounceFn.ts:6–56  ·  view source on GitHub ↗
(
  callback: StartFn<T>,
  delay: number,
  minimumTime?: number,
)

Source from the content-addressed store, hash-verified

4export type CancelEvent = () => void;
5
6export default function useDebounceFn<T = unknown>(
7 callback: StartFn<T>,
8 delay: number,
9 minimumTime?: number,
10): [StartFn<T>, CancelEvent] {
11 const timeoutRef = useRef<number>();
12 const callbackRef = useRef(callback);
13 const lastExecutionRef = useRef<Date>();
14
15 useEffect(() => {
16 callbackRef.current = callback;
17 }, [callback]);
18
19 useEffect(() => {
20 return () => window.clearTimeout(timeoutRef.current);
21 }, []);
22
23 const memoizedCallback = useCallback(
24 (args?: T) => {
25 // We should ensure the last execution + minimum time is less than the current time
26 if (
27 lastExecutionRef.current &&
28 minimumTime &&
29 lastExecutionRef.current.getTime() + minimumTime > new Date().getTime()
30 ) {
31 return;
32 }
33 if (timeoutRef.current) {
34 window.clearTimeout(timeoutRef.current);
35 }
36 timeoutRef.current = window.setTimeout(() => {
37 lastExecutionRef.current = new Date();
38 timeoutRef.current = undefined;
39 callbackRef.current?.(args);
40 }, delay);
41 },
42 [delay, timeoutRef, callbackRef, lastExecutionRef, minimumTime],
43 );
44
45 const cancelCallback = useCallback(() => {
46 if (timeoutRef.current) {
47 window.clearTimeout(timeoutRef.current);
48 timeoutRef.current = undefined;
49 }
50 }, [timeoutRef]);
51
52 return useMemo(
53 () => [memoizedCallback, cancelCallback],
54 [memoizedCallback, cancelCallback],
55 );
56}

Callers 15

PostsSearchFunction · 0.85
MarkdownFunction · 0.85
GiftPlusModalComponentFunction · 0.85
PreferenceOptionsFormFunction · 0.85
ReaderPostModalFunction · 0.85
SquadMemberModalFunction · 0.85
BasePostModalFunction · 0.85
EditTagFunction · 0.85
BaseDrawerFunction · 0.85
AnimatedDrawerFunction · 0.85
ProfileLocationFunction · 0.85
GifPopoverFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected