Skip to content

Instantly share code, notes, and snippets.

@drianoaz
Created March 18, 2022 22:19
Show Gist options
  • Save drianoaz/20864c59846e03c53f90ae819f21bf4d to your computer and use it in GitHub Desktop.
Save drianoaz/20864c59846e03c53f90ae819f21bf4d to your computer and use it in GitHub Desktop.
A simple use react hook that makes create throttled functions easy
const MyComponent = () => {
const callbackWithThrottle = useThrottle(() => {
console.log("this fires after 3 seconds after last click")
}, 3000);
return <button onClick={callbackWithThrottle}>Click me</button>
}
```
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