Throttled value hook that fires first, then once per interval
A reading-progress bar listens to scroll events, which fire dozens of times per second. Re-rendering the bar and sending an analytics event on every one is wasteful, but waiting until scrolling stops (debouncing) makes the bar freeze while the user scrolls. Throttling sits in between: react to the first change right away, then at most once per interval while changes keep coming, and always end on the latest value. Implement a React hook, useThrottledValue, that returns a throttled copy of a value.
function useThrottledValue<T>(value: T, interval: number): T
The hook returns a value we call throttled. Each time throttled changes, a window of interval ms opens.
throttled is value. Mounting does not open a window.value changes and no window is open, throttled becomes the new value right away, without waiting for a timer, and a window opens.value changes while a window is open, throttled keeps its current value. When the window closes, if the latest value differs from throttled (compare with Object.is), throttled becomes the latest value, which opens a new window. Values that were replaced before the window closed are skipped.value equals throttled (for example, it changed and then changed back), nothing happens and no new window opens. Once a window has closed with nothing waiting, no timer may be left pending.interval is 0 or negative, there is no throttling: throttled always equals value.function ReadingProgress() {
const scrollY = useScrollY(); // changes on every scroll event
const shownY = useThrottledValue(scrollY, 200);
useEffect(() => analytics.track('progress', shownY), [shownY]);
return <ProgressBar value={shownY} />;
}
// interval 300, value starts at 0
// t = 0 value 40 throttled 40 (no window was open: applied right away; window until 300)
// t = 100 value 90 throttled 40
// t = 200 value 150 throttled 40
// t = 300 throttled 150 (window closed with a newer value; new window until 600)
// t = 400 value 210 throttled 150
// t = 600 throttled 210 (new window until 900)
// t = 900 nothing changed, nothing happens
// t = 1500 value 260 throttled 260 (no window open: applied right away)
ReactDOM.flushSync. Some tests record every throttled value that was committed.setTimeout, clearTimeout, setInterval, clearInterval, Date.now and performance.now with a fake clock and move it forward by exact amounts. Some tests count the timers that are still pending.Object.assign(window, { useThrottledValue }); below “Do not edit below this line”. The tests use it to call your hook.