How to Fix Throttled Callback in React
DodaTech
Updated 2026-06-26
1 min read
The Problem
In this quick-fix, you'll learn how to implement throttled callbacks correctly in React. This matters because throttled functions recreate every render losing state. In real-world applications, this pattern appears in scroll handlers resize handlers rate-limited API calls.
The Wrong Way
function ScrollTracker() {
const [pos, setPos] = useState(0);
const throttledHandler = throttle(() => setPos(window.scrollY), 200);
useEffect(() => {
window.addEventListener("scroll", throttledHandler);
return () => window.removeEventListener("scroll", throttledHandler);
}, [throttledHandler]);
return <div>{pos}</div>;
}
throttledHandler re-created every render listener re-attaches
The Right Way
function ScrollTracker() {
const [pos, setPos] = useState(0);
const throttledRef = useRef(throttle(() => setPos(window.scrollY), 200));
useEffect(() => {
window.addEventListener("scroll", throttledRef.current);
return () => window.removeEventListener("scroll", throttledRef.current);
}, []);
return <div>{pos}</div>;
}
Stable throttle instance listener added once removed on unmount
Prevention
- Use refs for throttled functions to maintain stable instance
- Create throttle outside component or use ref
- Clean up throttled listeners in useEffect
FAQ
This guide is brought to you by DodaTech -- built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
← Previous
How to Fix Stale Closure in useCallback
Next →
How to Fix React Captured Value in Closures
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro