useThrottledCallback
useThrottledCallback is a React hook that returns a throttled version of the provided callback function. The throttled callback will only be invoked at most once per specified interval.
Interface
ts
function useThrottledCallback<T>(options: Object): (nextValue: T) => void;Parameters
- optionsrequired · Object
The options object.
- options.onChangerequired · (newValue: T) => void
The callback to throttle. A call with the same value as the last forwarded one is skipped.
- options.timeThresholdrequired · number
The number of milliseconds to throttle invocations to.
- options.edgesArray<'leading' | 'trailing'> · ['leading', 'trailing']
An optional array specifying whether the function should be invoked on the leading edge, trailing edge, or both.
- options.onChangerequired · (newValue: T) => void
Return Value
- (nextValue: T) => void
throttled function that forwards the value to
onChangeat most once per interval.
Example
tsx
import { useThrottledCallback } from 'react-simplikit';
import { useState } from 'react';
function ScrollPosition() {
const [scrollTop, setScrollTop] = useState(0);
const setScrollTopThrottled = useThrottledCallback({
onChange: setScrollTop,
timeThreshold: 200,
});
return (
<div onScroll={e => setScrollTopThrottled(e.currentTarget.scrollTop)}>
<p>Scrolled {scrollTop}px</p>
</div>
);
}