Skip to content

Instantly share code, notes, and snippets.

@PhilipWee
Last active June 19, 2024 05:54
Show Gist options
  • Save PhilipWee/3b0efbe1ec72300b61c17c2d2a0d593f to your computer and use it in GitHub Desktop.
Save PhilipWee/3b0efbe1ec72300b61c17c2d2a0d593f to your computer and use it in GitHub Desktop.
A simple typescript hook for debouncing functions
import { useRef, useEffect } from "react";
type Timer = ReturnType<typeof setTimeout>;
type SomeFunction = (...args: any[]) => void;
/**
*
* @param func The original, non debounced function (You can pass any number of args to it)
* @param delay The delay (in ms) for the function to return
* @returns The debounced function, which will run only if the debounced function has not been called in the last (delay) ms
*/
export function useDebounce<Func extends SomeFunction>(
func: Func,
delay = 1000
) {
const timer = useRef<Timer>();
useEffect(() => {
return () => {
if (!timer.current) return;
clearTimeout(timer.current);
};
}, []);
const debouncedFunction = ((...args) => {
const newTimer = setTimeout(() => {
func(...args);
}, delay);
clearTimeout(timer.current);
timer.current = newTimer;
}) as Func;
return debouncedFunction;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment