Skip to content

Instantly share code, notes, and snippets.

@PhilipWee
Created August 15, 2022 07:43
Show Gist options
  • Save PhilipWee/deba9fd3e0cd2f0878090c09e3a7f179 to your computer and use it in GitHub Desktop.
Save PhilipWee/deba9fd3e0cd2f0878090c09e3a7f179 to your computer and use it in GitHub Desktop.
import { useState } from "react";
type SomeFunction = (...args: any[]) => void;
type Timer = ReturnType<typeof setTimeout>;
function useDebounce<Func extends SomeFunction>(func: Func, delay) {
const [timer, setTimer] = useState<Timer>(); //Create timer state
const debouncedFunction = ((...args) => {
const newTimer = setTimeout(() => {
func(...args);
}, delay);
clearTimeout(timer); //Cancel previous timers
setTimer(newTimer); //Save latest timer
}) as Func;
return debouncedFunction;
}
module.exports = { useDebounce };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment