Update hooks/useDebounce.ts
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
This commit is contained in:
parent
c1bc573dcb
commit
502b52e4f0
|
|
@ -4,12 +4,16 @@ import { useCallback, useRef } from 'react';
|
||||||
|
|
||||||
export function useDebounce(callback: () => void, delay: number) {
|
export function useDebounce(callback: () => void, delay: number) {
|
||||||
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
|
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||||
|
const callbackRef = useRef(callback);
|
||||||
|
|
||||||
|
// Keep callback ref up to date
|
||||||
|
callbackRef.current = callback;
|
||||||
|
|
||||||
return useCallback(() => {
|
return useCallback(() => {
|
||||||
if(timeoutRef.current) {
|
if (timeoutRef.current) {
|
||||||
clearTimeout(timeoutRef.current);
|
clearTimeout(timeoutRef.current);
|
||||||
}
|
}
|
||||||
|
|
||||||
timeoutRef.current = setTimeout(callback, delay);
|
timeoutRef.current = setTimeout(() => callbackRef.current(), delay);
|
||||||
}, [callback, delay])
|
}, [delay])
|
||||||
}
|
}
|
||||||
Loading…
Reference in New Issue