Created
March 18, 2022 22:19
-
-
Save drianoaz/20864c59846e03c53f90ae819f21bf4d to your computer and use it in GitHub Desktop.
A simple use react hook that makes create throttled functions easy
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
const MyComponent = () => { | |
const callbackWithThrottle = useThrottle(() => { | |
console.log("this fires after 3 seconds after last click") | |
}, 3000); | |
return <button onClick={callbackWithThrottle}>Click me</button> | |
} | |
``` |
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 { useCallback, useRef } from 'react'; | |
export function useThrottle<T>(callback: (args: T) => void, delay: number) { | |
const timer = useRef<NodeJS.Timeout>(); | |
return useCallback( | |
(args: T) => { | |
if (timer.current) { | |
clearTimeout(timer.current); | |
} | |
timer.current = setTimeout(() => { | |
callback(args); | |
}, delay); | |
}, | |
[callback, delay], | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment