function useThrottler<TFn>(fn, options): Throttler<TFn>
function useThrottler<TFn>(fn, options): Throttler<TFn>
定义于:react-pacer/src/throttler/useThrottler.ts:42
一个低级别的 React 钩子,用于创建一个 Throttler 实例,该实例限制所提供函数的执行频率。
此钩子设计灵活且与状态管理无关——它仅返回一个节流器实例,您可以将其与任何状态管理解决方案(useState、Redux、Zustand、Jotai 等)集成。有关直接与 React 的 useState 集成的更简单、更高级别的钩子,请参阅 useThrottledState。
节流确保函数在指定的时间窗口内最多执行一次, 无论它被调用多少次。这对于限制昂贵的操作或 UI 更新的速率非常有用。
• TFn extends AnyFunction
TFn
ThrottlerOptions<TFn>
Throttler<TFn>
// 带自定义状态的基础节流
const [value, setValue] = useState(0);
const throttler = useThrottler(setValue, { wait: 1000 });
// 结合 Redux
const dispatch = useDispatch();
const throttler = useThrottler(
(value) => dispatch(updateAction(value)),
{ wait: 1000 }
);
// 结合任何状态管理器
const throttler = useThrottler(
(value) => stateManager.setState(value),
{
wait: 2000,
leading: true, // 首次调用立即执行
trailing: false // 跳过尾随边缘更新
}
);
// 带自定义状态的基础节流
const [value, setValue] = useState(0);
const throttler = useThrottler(setValue, { wait: 1000 });
// 结合 Redux
const dispatch = useDispatch();
const throttler = useThrottler(
(value) => dispatch(updateAction(value)),
{ wait: 1000 }
);
// 结合任何状态管理器
const throttler = useThrottler(
(value) => stateManager.setState(value),
{
wait: 2000,
leading: true, // 首次调用立即执行
trailing: false // 跳过尾随边缘更新
}
);