Created
January 4, 2021 22:40
-
-
Save noahlt/8a01136488fdce300d4b293bf2fcd3f8 to your computer and use it in GitHub Desktop.
React Hook for throttled state value
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
// 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