Skip to content

Instantly share code, notes, and snippets.

@ToTheHit
Last active August 26, 2021 18:01
Show Gist options
  • Save ToTheHit/3da32f28cbe6fa3172360a49c5dd9fcc to your computer and use it in GitHub Desktop.
Save ToTheHit/3da32f28cbe6fa3172360a49c5dd9fcc to your computer and use it in GitHub Desktop.
import { useState, useEffect, useRef } from 'react';
export default function useThrottle(value, limit) {
const [throttledValue, setThrottledValue] = useState(value);
const lastRan = useRef(Date.now());
useEffect(
() => {
const handler = setTimeout(function() {
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