Last active
August 26, 2021 18:01
-
-
Save ToTheHit/3da32f28cbe6fa3172360a49c5dd9fcc to your computer and use it in GitHub Desktop.
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 { 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