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
| Name | Type | Required | Description |
|---|---|---|---|
initialState | T | (() => T) | Yes | Initial value or lazy initializer. |
interval | number | No | Throttle window in ms. Defaults to 100. |
options.leading | boolean | No | Commit first update in a throttle window. |
options.trailing | boolean | No | Commit latest queued update at window end. |
Return value
| Position | Type | Description |
|---|---|---|
0 | T | Current committed value. |
1 | Dispatch<SetStateAction<T>> | Throttled setter function. |
2 | ThrottledStateStats | { 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 StackBlitzCode 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>
);
}