Implementing useThrottle Custom Hook
Build a useThrottle hook that limits how often a value updates during rapid events like scrolling.
Throttle Is Harder Than Debounce
Debounce simply resets a timer on each event. Throttle must actively track when the last execution happened and decide whether enough time has passed for another one. This requires persisting a timestamp between renders, making the implementation slightly more involved than debounce.
Using useRef for lastRunTime
The last-execution timestamp must persist across renders without triggering re-renders itself, making useRef the right tool. Store the timestamp as const lastRunTime = useRef(Date.now()). Unlike state, updating a ref does not cause a re-render, so the throttle logic runs efficiently without extra cycles.
All lessons in this course
- Why Debounce and Throttle Matter in UIs
- Implementing useDebounce Custom Hook
- Implementing useThrottle Custom Hook
- Practical Applications: Search, Scroll, Resize