Created
January 8, 2024 19:33
-
-
Save GalindoSVQ/5334a83ded855a5118222260062aed62 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 * 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://stackblitz.com/edit/stackblitz-starters-d8tyma?file=src%2FApp.tsx