Skip to content

Instantly share code, notes, and snippets.

@chaance
Last active April 9, 2020 19:51
Show Gist options
  • Save chaance/96933ded618ba9199f3e3b5c619d10ba to your computer and use it in GitHub Desktop.
Save chaance/96933ded618ba9199f3e3b5c619d10ba to your computer and use it in GitHub Desktop.
Simple debounce hook for React
function useDebounce<F extends Function>(
func: F,
delay: number,
immediate?: boolean
) {
let debouncedFunc = useRef(func);
useEffect(() => {
let timeout: number | null;
debouncedFunc.current = (((...args: any[]) => {
let callNow = immediate && timeout == null;
let later = () => {
timeout = null;
if (!immediate) {
func(...args);
}
};
window.clearTimeout(timeout!);
timeout = window.setTimeout(later, delay);
if (callNow) {
func(...args);
}
}) as unknown) as F;
return function () {
window.clearTimeout(timeout!);
};
}, [func, delay, immediate]);
return debouncedFunc.current;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment