Code Snippets
/

React useThrottle Hook

React useThrottle Hook

Throttling caps the rate at which a value updates while still letting changes through at a steady cadence. This snippet covers the basic useThrottle that emits at most once per window, a useThrottledCallback variant for wrapping functions, and the leading-plus-trailing edge form that keeps the first and last events without dropping the tail. Use it for scroll handlers, mouse trackers, and any high-frequency stream you need to sample.

JavaScript
Easy
3 snippets
react
hooks
performance-optimization
code-template

927 views

5

function useThrottle(value, interval = 200) {
    const [throttled, setThrottled] = useState(value);
    const lastUpdateRef = useRef(Date.now());
    useEffect(() => {
        const elapsed = Date.now() - lastUpdateRef.current;
        if (elapsed >= interval) {
            lastUpdateRef.current = Date.now();
            setThrottled(value);
            return;
        }
        const id = setTimeout(() => {
            lastUpdateRef.current = Date.now();
            setThrottled(value);
        }, interval - elapsed);
        return () => clearTimeout(id);
    }, [value, interval]);
    return throttled;
}

function useState(v) { return [v, () => {}]; }
function useEffect(fn) { fn(); }
function useRef(v) { return { current: v }; }
console.log('throttled:', useThrottle(42, 100));

The hook tracks the last update time in a ref and only forwards the current value when the elapsed gap is long enough. If the value changed too soon, a setTimeout schedules the next emission for the remaining time so the tail of a fast burst is not lost. This is the difference from a debounce: throttle still emits at a steady cadence during sustained input, while debounce only emits after activity stops. Use it for mouse-move handlers, scroll positions, or any sensor stream where intermediate samples are useful.