useThrottledValue
useThrottledValue is a React hook that returns a throttled copy of the given value. The caller keeps owning the state; the returned value follows it at most once per wait milliseconds, which is useful for driving expensive renders from scroll position, pointer position, or an element's size on resize.
On the first render and on the server the value is returned as is. A change is never scheduled on mount, so the first change after mount is applied immediately when leading is true. If both leading and trailing are false, the returned value never updates.
The value is compared by reference. Passing a new object or array on every render keeps the returned value updating every wait milliseconds; stabilize the reference first, for example with usePreservedReference.
Interface
function useThrottledValue<T>(
value: T,
wait: number,
options: ThrottleOptions
): T;Parameters
- valuerequired · T
The value to throttle.
- waitrequired · number
The length of the throttle window in milliseconds.
- optionsThrottleOptions
Configuration options for throttle behavior.
- options.leadingboolean · true
If
true, the first change in a window is applied immediately. - options.trailingboolean · true
If
true, the last change in a window is appliedwaitmilliseconds after that change.
- options.leadingboolean · true
Return Value
- T
throttled value.
Example
import { useThrottledValue } from 'react-simplikit';
import { useState } from 'react';
function ScrollProgress() {
const [scrollY, setScrollY] = useState(0);
const throttledScrollY = useThrottledValue(scrollY, 100);
return (
<div onScroll={e => setScrollY(e.currentTarget.scrollTop)}>
<ProgressBar position={throttledScrollY} />
</div>
);
}