Last active
April 9, 2020 19:51
-
-
Save chaance/96933ded618ba9199f3e3b5c619d10ba to your computer and use it in GitHub Desktop.
Simple debounce hook for React
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
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