57Implement useThrottle() for values and callbacks
mediumAbout 35 minutesCodingreacthookstimersrefs
Problem
Implement two hooks:
useThrottle(value, interval): returns a copy ofvaluethat updates at most once perintervalms. The first change after a quiet period shows immediately; changes during the interval are merged into one trailing update with the latest value.useThrottledCallback(callback, interval): returns a stable function that calls the latestcallbackat most once perintervalms, with a trailing call for the last arguments.
function ScrollProgress() {
const [y, setY] = useState(0);
const onScroll = useThrottledCallback(() => setY(window.scrollY), 100);
useEffect(() => {
window.addEventListener("scroll", onScroll);
return () => window.removeEventListener("scroll", onScroll);
}, [onScroll]); // stable, so the listener is added once
return <progress value={y} max={document.body.scrollHeight} />;
}Requirements
useThrottledCallbackreturns the same function on every render, yet always calls the callback from the latest render (no stale closures).- Both hooks clear their timers on unmount.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
App.jsxReact + DOM
Step-by-step
Keep the throttled value in state and the time of the last update in a ref, lastRun. Start it at 0, so the effect after the first render counts as a run instead of scheduling a pointless timer that would delay the next real change.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 5 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.