Skip to content

Instantly share code, notes, and snippets.

@hi-ogawa
Last active November 14, 2022 07:10
Show Gist options
  • Save hi-ogawa/9ca2be24de5954db81906dab2437a91e to your computer and use it in GitHub Desktop.
Save hi-ogawa/9ca2be24de5954db81906dab2437a91e to your computer and use it in GitHub Desktop.
use-debounced-function.ts
//
// example:
// <button onClick={useDebouncedFunction(() => console.log("debounced?"), 500)} />
//
export function useDebouncedFunction<T extends (...args: any[]) => void>(
original: T,
ms: number
): (...args: Parameters<T>) => void {
const [call, setCall] = React.useState<() => void>();
// make original callback stable for simplicity
const originalRef = React.useRef(original);
originalRef.current = original;
React.useEffect(() => {
if (call) {
const timeout = window.setTimeout(call, ms);
return () => window.clearTimeout(timeout);
}
}, [call, ms]);
const debounced = React.useCallback(
(...args: Parameters<T>) => {
setCall(_prev => () => originalRef.current(...args));
},
[original]
);
return debounced;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment