ReactMedium

Throttle in React?

Throttling limits how often a function runs during continuous events, for example at most once every 100ms while scrolling or resizing, while still running regularly during the activity (unlike debounce, which waits for a pause). In React, create the throttled handler once, attach it in an effect with cleanup, and prefer requestAnimationFrame for visual updates or browser APIs like IntersectionObserver that avoid scroll listeners entirely.

When to throttle

  • Scroll position tracking (progress bars, "back to top" buttons, sticky headers).
  • Window resize calculations.
  • Pointer or mouse move handlers (drag, drawing, cursor sharing).
  • Rate-limiting API calls during continuous actions (sending cursor positions over a WebSocket).

Implementations

  • Timestamp-based: run if enough time has passed since the last call; optionally schedule a trailing call so the final position is not missed.
  • requestAnimationFrame: at most once per frame (about 16ms at 60Hz), synchronized with painting. Best for visual updates.
  • Libraries: lodash-es/throttle or es-toolkit with leading and trailing options.

React specifics

  • Do not create the throttled function in render without memoization; it would reset every render.
  • Use { passive: true } for scroll and touch listeners so the browser can scroll smoothly.
  • Clean up listeners and pending timers or animation frames.
  • Avoid storing every event in state; store derived values (for example a boolean "scrolled past header") to minimize re-renders.

Often better than throttling

  • IntersectionObserver for "is this element visible" (lazy loading, infinite scroll, active section).
  • CSS position: sticky and scroll-driven animations for purely visual effects.

Code example

tsx
1import { useEffect, useState } from "react";
2
3function throttle<A extends unknown[]>(fn: (...args: A) => void, wait: number) {
4 let last = 0;
5 let trailing: ReturnType<typeof setTimeout> | undefined;
6 const run = (...args: A) => {
7 const now = Date.now();
8 const remaining = wait - (now - last);
9 clearTimeout(trailing);
10 if (remaining <= 0) {
11 last = now;
12 fn(...args);
13 } else {
14 trailing = setTimeout(() => { last = Date.now(); fn(...args); }, remaining); // don't miss the final event
15 }
16 };
17 run.cancel = () => clearTimeout(trailing);
18 return run;
19}
20
21export function ScrollProgress() {
22 const [progress, setProgress] = useState(0);
23
24 useEffect(() => {
25 const update = throttle(() => {
26 const max = document.documentElement.scrollHeight - window.innerHeight;
27 setProgress(max > 0 ? Math.round((window.scrollY / max) * 100) : 0);
28 }, 100); // at most 10 updates per second
29
30 window.addEventListener("scroll", update, { passive: true });
31 update();
32 return () => {
33 window.removeEventListener("scroll", update);
34 update.cancel();
35 };
36 }, []);
37
38 return <div style={{ position: "fixed", top: 0, left: 0, height: 4, width: `${progress}%`, background: "#4f46e5" }} />;
39}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app