Skip to content

Instantly share code, notes, and snippets.

@alii
Created July 7, 2021 00:14
Show Gist options
  • Save alii/2d0772d39fd6ccb867fa9066ce9dd8a3 to your computer and use it in GitHub Desktop.
Save alii/2d0772d39fd6ccb867fa9066ce9dd8a3 to your computer and use it in GitHub Desktop.
use-throttle.ts
export function useThrottle<T>(value: T, limit = 1000) {
const [throttledValue, setThrottledValue] = useState(value);
const lastRan = useRef(Date.now());
useEffect(() => {
const handler = setTimeout(() => {
if (Date.now() - lastRan.current >= limit) {
setThrottledValue(value);
lastRan.current = Date.now();
}
}, limit - (Date.now() - lastRan.current));
return () => {
clearTimeout(handler);
};
}, [value, limit]);
return throttledValue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment