Skip to content

Instantly share code, notes, and snippets.

@noahlt
Created January 4, 2021 22:40
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 noahlt/8a01136488fdce300d4b293bf2fcd3f8 to your computer and use it in GitHub Desktop.
Save noahlt/8a01136488fdce300d4b293bf2fcd3f8 to your computer and use it in GitHub Desktop.
React Hook for throttled state value
// Usage:
const [value, setValue] = useThrottledState(0, 1000, true);
// As long as `live` is true, every `updateInterval` milliseconds, `value` will
// get updated (causing the calling component to re-render). Meanwhile, you can
// call `setValue` as frequently as you want without causing a re-render each time.
function useThrottledState(initialValue, updateInterval, live) {
const realValueRef = useRef(initialValue);
const setRealValue = (xf) => {
realValueRef.current = isFunction(xf) ? xf(realValueRef.current) : xf;
};
const [throttledValue, setThrottledValue] = useState(initialValue);
useEffect(() => {
if (live) {
var intervalID = setInterval(() => {
setThrottledValue(realValueRef.current);
}, updateInterval);
} else {
setThrottledValue(realValueRef.current)
}
return () => clearInterval(intervalID);
}, [live]);
return [throttledValue, setRealValue];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment