Skip to content

Instantly share code, notes, and snippets.

@hanbzu
Created November 11, 2019 17:11
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 hanbzu/e76a976e185c5523c5ba175206e402ac to your computer and use it in GitHub Desktop.
Save hanbzu/e76a976e185c5523c5ba175206e402ac to your computer and use it in GitHub Desktop.
A React hook that throttles a value
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