Created
March 30, 2021 14:14
-
-
Save loonywizard/c2813222ff41b7fd1479793414dc4c01 to your computer and use it in GitHub Desktop.
React useThrottle hook
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 { 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