Created
August 15, 2022 07:43
-
-
Save PhilipWee/deba9fd3e0cd2f0878090c09e3a7f179 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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