All hooks / Timers

useThrottledCallback

268 B minified and brotliedSourceMarkdown✓ Works in all modern browsers

Returns a throttled version of callback: it runs right away, then at most once every intervalMs while calls keep coming, and once more at the end with the arguments of the last call, so the final value is never lost. The returned function is stable and always runs the latest callback.

A pending call is dropped on unmount (call flush first to keep it) and when intervalMs changes.

Import

import { useThrottledCallback } from '@vincent.ri/react-tils'
// or only this hook
import { useThrottledCallback } from '@vincent.ri/react-tils/useThrottledCallback'

Usage

const sendCursor = useThrottledCallback((x: number, y: number) => socket.send({ x, y }), 100)
return <div onPointerMove={(e) => sendCursor(e.clientX, e.clientY)} />

Live demo

Drag the slider: saves every 500 ms, then once at the end.

events 0 · saves 0 · saved 50

When to use it

Work that should keep happening during a burst, not only after it: live search results while typing, saving a slider's position, sending "typing…" or cursor positions to a server, analytics for scroll depth.

When not to

It should run once after the user stops (autosave a draft, validate); use useDebouncedCallback. To follow scroll or size, use useWindowScroll, useElementScroll, or useElementSize, which already avoid extra re-renders. For drawing on every frame, use useAnimationFrame.

API

function useThrottledCallback<A extends unknown[]>(callback: (...args: A) => void, intervalMs: number): ThrottledFunction<A>
ParameterDescription
callbackThe function to throttle. Can change every render.
intervalMsRun at most once per this many milliseconds.

Returns The throttled function, with cancel, flush, and pending.

Types

/** Same shape as a debounced function: callable, with `cancel`, `flush`, and `pending`. */
export type ThrottledFunction<A extends unknown[]> = DebouncedFunction<A>;

Browser support

Uses only long-established browser features, so it works wherever React does.

First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).

Coming from another library?

Other libraries call this useThrottleFn, useThrottleCallback, useThrottle.