Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Alimjanov-Ibragim/d89887f383d5388669dd1ece05e4901b to your computer and use it in GitHub Desktop.
Save Alimjanov-Ibragim/d89887f383d5388669dd1ece05e4901b to your computer and use it in GitHub Desktop.
React useThrottle hook
import { useEffect, useRef, useState } from 'react'
function useThrottle<T>(value: T, interval = 500): T {
const [throttledValue, setThrottledValue] = useState<T>(value)
const lastExecuted = useRef<number>(Date.now())
useEffect(() => {
if (Date.now() >= lastExecuted.current + interval) {
lastExecuted.current = Date.now()
setThrottledValue(value)
} else {
const timerId = setTimeout(() => {
lastExecuted.current = Date.now()
setThrottledValue(value)
}, interval)
return () => clearTimeout(timerId)
}
}, [value, interval])
return throttledValue
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment