Last active
November 14, 2022 07:10
-
-
Save hi-ogawa/9ca2be24de5954db81906dab2437a91e to your computer and use it in GitHub Desktop.
use-debounced-function.ts
This file contains hidden or 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
// | |
// example: | |
// <button onClick={useDebouncedFunction(() => console.log("debounced?"), 500)} /> | |
// | |
export function useDebouncedFunction<T extends (...args: any[]) => void>( | |
original: T, | |
ms: number | |
): (...args: Parameters<T>) => void { | |
const [call, setCall] = React.useState<() => void>(); | |
// make original callback stable for simplicity | |
const originalRef = React.useRef(original); | |
originalRef.current = original; | |
React.useEffect(() => { | |
if (call) { | |
const timeout = window.setTimeout(call, ms); | |
return () => window.clearTimeout(timeout); | |
} | |
}, [call, ms]); | |
const debounced = React.useCallback( | |
(...args: Parameters<T>) => { | |
setCall(_prev => () => originalRef.current(...args)); | |
}, | |
[original] | |
); | |
return debounced; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment