Skip to main content

useThrottledState

Description and use case

useThrottledState limits high-frequency state updates (pointer, resize, scroll) while reporting dropped updates for tuning.

API signature

function useThrottledState<T>(
initialState: T | (() => T),
interval?: number,
options?: UseThrottledStateOptions
): [T, Dispatch<SetStateAction<T>>, ThrottledStateStats]

Parameters

NameTypeRequiredDescription
initialStateT | (() => T)YesInitial value or lazy initializer.
intervalnumberNoThrottle window in ms. Defaults to 100.
options.leadingbooleanNoCommit first update in a throttle window.
options.trailingbooleanNoCommit latest queued update at window end.

Return value

PositionTypeDescription
0TCurrent committed value.
1Dispatch<SetStateAction<T>>Throttled setter function.
2ThrottledStateStats{ droppedUpdates, totalUpdates } counters.

Live interactive demo (StackBlitz)

This demo uses an embedded StackBlitz sandbox. Load it inline or open it in a new tab.

Open demo in StackBlitz

Code example

import {useThrottledState} from 'react-perf-hooks';

export function PointerTracker() {
const [point, setPoint, stats] = useThrottledState({x: 0, y: 0}, 100, {
leading: true,
trailing: true,
});

return (
<div
onPointerMove={(event) => {
setPoint({x: event.clientX, y: event.clientY});
}}>
<p>
Pointer: {point.x}, {point.y}
</p>
<p>Dropped updates: {stats.droppedUpdates}</p>
</div>
);
}

Companion article