forked from jnsahaj/tweakcn
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-debounced-callback.ts
More file actions
41 lines (35 loc) · 1.05 KB
/
use-debounced-callback.ts
File metadata and controls
41 lines (35 loc) · 1.05 KB
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
import { useRef, useEffect, useCallback } from "react";
export function useDebouncedCallback<A extends unknown[]>(
callback: (...args: A) => void,
wait: number
) {
// Use a ref to store the latest callback.
const callbackRef = useRef(callback);
useEffect(() => {
callbackRef.current = callback;
}, [callback]);
// Use a ref to store the timeout ID
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
// Cleanup function
useEffect(() => {
// Clear the timeout when the component unmounts or dependencies change
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, [wait]); // Rerun effect only if wait time changes
// The debounced function
const debouncedCallback = useCallback(
(...args: A) => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(() => {
callbackRef.current(...args);
}, wait);
},
[wait] // Dependency is only the wait time
);
return debouncedCallback;
}