Skip to content

Instantly share code, notes, and snippets.

@GalindoSVQ
Created January 8, 2024 19:33
Show Gist options
  • Save GalindoSVQ/5334a83ded855a5118222260062aed62 to your computer and use it in GitHub Desktop.
Save GalindoSVQ/5334a83ded855a5118222260062aed62 to your computer and use it in GitHub Desktop.
import * as React from 'react';
export default function useThrottle(value, interval = 500) {
const [throttledValue, setThrottledValue] = React.useState(value);
const lastUpdated = React.useRef(null);
React.useEffect(() => {
const now = Date.now();
if (lastUpdated.current && now >= lastUpdated.current + interval) {
lastUpdated.current = now;
setThrottledValue(value);
} else {
const id = window.setTimeout(() => {
lastUpdated.current = now;
setThrottledValue(value);
}, interval);
return () => window.clearTimeout(id);
}
}, [value, interval]);
return throttledValue;
}
@GalindoSVQ
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment