Created
November 11, 2019 17:11
-
-
Save hanbzu/e76a976e185c5523c5ba175206e402ac to your computer and use it in GitHub Desktop.
A React hook that throttles a value
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 React from "react"; | |
export default function useThrottle(val, ms) { | |
const [throttledVal, setThrottledVal] = React.useState(val); | |
const latestVal = React.useRef(val); | |
React.useEffect(() => { | |
latestVal.current = val; | |
}, [val]); | |
// The timer is only recreated if ms changes | |
React.useEffect(() => { | |
const handle = setInterval(() => { | |
// The state only changes every "ms" miliseconds | |
// We use a reference to make sure we use the latest val | |
setThrottledVal(latestVal.current); | |
}, ms); | |
return () => clearInterval(handle); | |
}, [ms]); | |
return throttledVal; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment