Skip to content

Commit

Permalink
Update use-debounced-callback.ts to add a flush method to the returne…
Browse files Browse the repository at this point in the history
…d callback as well as give an option to simply flush on unmount
  • Loading branch information
scamden committed Dec 19, 2024
1 parent 3216b36 commit 22e1e48
Showing 1 changed file with 37 additions and 14 deletions.
Original file line number Diff line number Diff line change
@@ -1,19 +1,42 @@
import { useCallback, useEffect, useRef } from 'react';
import { useCallbackRef } from '../use-callback-ref/use-callback-ref';
import { useCallback, useEffect, useRef } from "react";
import { useCallbackRef } from "../use-callback-ref/use-callback-ref";

export function useDebouncedCallback<T extends (...args: any[]) => any>(
callback: T,
delay: number
callback: T,
options: number | { delay: number; flushOnUnmount?: boolean },
) {
const handleCallback = useCallbackRef(callback);
const debounceTimerRef = useRef(0);
useEffect(() => () => window.clearTimeout(debounceTimerRef.current), []);
const delay = typeof options === "number" ? options : options.delay;
const flushOnUnmount =
typeof options === "number" ? false : options.flushOnUnmount;
const handleCallback = useCallbackRef(callback);
const debounceTimerRef = useRef(0);

return useCallback(
(...args: Parameters<T>) => {
window.clearTimeout(debounceTimerRef.current);
debounceTimerRef.current = window.setTimeout(() => handleCallback(...args), delay);
},
[handleCallback, delay]
);
const lastCallback: ((...args: Parameters<T>) => void) & {
flush?: () => void;
} = useCallback(
(...args: Parameters<T>) => {
window.clearTimeout(debounceTimerRef.current);
const flush = () => {
if (debounceTimerRef.current !== 0) {
debounceTimerRef.current = 0;
handleCallback(...args);
}
};
lastCallback.flush = flush;
debounceTimerRef.current = window.setTimeout(flush, delay);
},
[handleCallback, delay],
);

useEffect(
() => () => {
window.clearTimeout(debounceTimerRef.current);
if (flushOnUnmount) {
lastCallback.flush?.();
}
},
[lastCallback, flushOnUnmount],
);

return lastCallback;
}

0 comments on commit 22e1e48

Please sign in to comment.