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<F extends (...args: any[]) => any>(
callback: F,
wait: number,
options?: { edges?: Array<'leading' | 'trailing'> }
): F & { cancel: () => void };Parameters
- callbackrequired · F
The function to throttle.
- waitrequired · number
The number of milliseconds to throttle invocations to.
- options{ edges?: Array<'leading' | 'trailing'> }
Options to control the behavior of the throttle.
- options.edgesArray<'leading' | 'trailing'> · ['leading', 'trailing']
An optional array specifying whether the function should be invoked on the leading edge, trailing edge, or both.
: The initial value is['leading', 'trailing'].
- options.edgesArray<'leading' | 'trailing'> · ['leading', 'trailing']
Return Value
- F & { cancel: () => void }
Returns the throttled function with a
cancelmethod to cancel any pending invocation.
Example
tsx
function SearchInput() {
const throttledSearch = useThrottledCallback((query: string) => {
console.log('Searching for:', query);
}, 300);
return <input onChange={e => throttledSearch(e.target.value)} />;
}