function useThrottledCallback<TFn>(fn, options): (...args) => void
function useThrottledCallback<TFn>(fn, options): (...args) => void
定义于: react-pacer/src/throttler/useThrottledCallback.ts:43
一个 React hook,用于创建一个回调函数的节流版本。此 hook 基本上是对从 @tanstack/pacer 导出的基本 throttle 函数的封装,但针对 React 进行了优化,具有响应式选项和稳定的函数引用。
节流函数将在指定的等待时间段内最多执行一次,无论调用多少次。如果在等待期间被多次调用,只有第一次调用会执行,后续的调用将被忽略,直到等待时间段结束。
与 useThrottler hook 相比,此 hook 提供了更简单的 API,非常适合基本节流需求。但是,它不会暴露底层的 Throttler 实例。
对于需要以下功能的进阶用法
请考虑改用 useThrottler hook。
• TFn extends AnyFunction
TFn
ThrottlerOptions<TFn>
Function
...Parameters<TFn>
void
// Throttle a window resize handler
const handleResize = useThrottledCallback(() => {
updateLayoutMeasurements();
}, {
wait: 100 // Execute at most once every 100ms
});
// Use in an event listener
useEffect(() => {
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, [handleResize]);
// Throttle a window resize handler
const handleResize = useThrottledCallback(() => {
updateLayoutMeasurements();
}, {
wait: 100 // Execute at most once every 100ms
});
// Use in an event listener
useEffect(() => {
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, [handleResize]);
您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。