框架
版本
防抖器 API 参考
节流器 API 参考
速率限制器 API 参考
队列 API 参考
批处理器 API 参考

使用速率限制器

函数:useRateLimiter()

ts
function useRateLimiter<TFn, TSelected>(
   fn, 
   options, 
selector): ReactRateLimiter<TFn, TSelected>
function useRateLimiter<TFn, TSelected>(
   fn, 
   options, 
selector): ReactRateLimiter<TFn, TSelected>

定义于:react-pacer/src/rate-limiter/useRateLimiter.ts:141

一个低级别的 React Hook,用于创建一个 RateLimiter 实例,以强制执行函数执行的速率限制。

此 Hook 的设计旨在灵活且独立于状态管理 - 它仅仅返回一个速率限制器实例,您可以将其集成到任何状态管理解决方案中(useState、Redux、Zustand、Jotai 等)。

速率限制是一种简单的“硬限制”方法,它允许在时间窗口内达到最大计数之前执行,然后阻止所有后续调用,直到窗口重置。与节流或防抖不同,它不尝试智能地间隔或合并执行。

速率限制器支持两种类型的窗口

  • 'fixed': 一个严格的窗口,在窗口期后重置。窗口内的所有执行都会计入限制,并且窗口会在期满后完全重置。
  • 'sliding': 一个滚动窗口,允许在旧的执行过期时进行新的执行。这提供了更一致的执行速率。

为了更平滑的执行模式

  • 当您希望在执行之间保持一致的间隔时,请使用节流(例如,UI 更新)。
  • 当您希望合并快速触发的事件时,请使用防抖(例如,搜索输入框)。
  • 仅当您需要强制执行硬限制时(例如,API 速率限制),才使用速率限制。

状态管理和选择器

该 Hook 使用 TanStack Store 进行响应式状态管理。`selector` 参数允许您指定哪些状态更改将触发重新渲染,通过防止不必要的重新渲染来优化性能。只有当您提供 `selector` 时,组件才会在选定的状态值发生变化时重新渲染。

默认情况下,将不会有响应式状态订阅,您必须通过提供 `selector` 函数来选择加入状态跟踪。这可以防止不必要的重新渲染,并让您完全控制组件何时更新。只有当您提供 `selector` 时,组件才会在选定的状态值发生变化时重新渲染。

可用的状态属性

  • executionCount: 已完成的函数执行次数
  • executionTimes:执行发生的时间戳数组,用于速率限制计算。
  • rejectionCount:由于速率限制而被拒绝的函数执行次数。

该 Hook 返回一个包含以下内容的对象的结构:

  • maybeExecute:遵循配置限制的速率限制函数。
  • getExecutionCount:返回成功执行的次数。
  • getRejectionCount:返回因速率限制而被拒绝的执行次数。
  • getRemainingInWindow:返回当前窗口中还允许多少次执行。
  • reset:重置执行计数和窗口计时。

类型参数

TFn extends AnyFunction

TSelected = {}

参数

fn

TFn

options

RateLimiterOptions<TFn>

选择器

(state) => TSelected

Returns (返回)

ReactRateLimiter<TFn, TSelected>

示例

tsx
// Default behavior - no reactive state subscriptions
const rateLimiter = useRateLimiter(apiCall, {
  limit: 5,
  window: 60000,
  windowType: 'sliding',
});

// Opt-in to re-render when execution count changes (optimized for tracking successful executions)
const rateLimiter = useRateLimiter(
  apiCall,
  {
    limit: 5,
    window: 60000,
    windowType: 'sliding',
  },
  (state) => ({ executionCount: state.executionCount })
);

// Opt-in to re-render when rejection count changes (optimized for tracking rate limit violations)
const rateLimiter = useRateLimiter(
  apiCall,
  {
    limit: 5,
    window: 60000,
    windowType: 'sliding',
  },
  (state) => ({ rejectionCount: state.rejectionCount })
);

// Opt-in to re-render when execution times change (optimized for window calculations)
const rateLimiter = useRateLimiter(
  apiCall,
  {
    limit: 5,
    window: 60000,
    windowType: 'sliding',
  },
  (state) => ({ executionTimes: state.executionTimes })
);

// Multiple state properties - re-render when any of these change
const rateLimiter = useRateLimiter(
  apiCall,
  {
    limit: 5,
    window: 60000,
    windowType: 'sliding',
  },
  (state) => ({
    executionCount: state.executionCount,
    rejectionCount: state.rejectionCount
  })
);

// Monitor rate limit status
const handleClick = () => {
  const remaining = rateLimiter.getRemainingInWindow();
  if (remaining > 0) {
    rateLimiter.maybeExecute(data);
  } else {
    showRateLimitWarning();
  }
};

// Access the selected state (will be empty object {} unless selector provided)
const { executionCount, rejectionCount } = rateLimiter.state;
// Default behavior - no reactive state subscriptions
const rateLimiter = useRateLimiter(apiCall, {
  limit: 5,
  window: 60000,
  windowType: 'sliding',
});

// Opt-in to re-render when execution count changes (optimized for tracking successful executions)
const rateLimiter = useRateLimiter(
  apiCall,
  {
    limit: 5,
    window: 60000,
    windowType: 'sliding',
  },
  (state) => ({ executionCount: state.executionCount })
);

// Opt-in to re-render when rejection count changes (optimized for tracking rate limit violations)
const rateLimiter = useRateLimiter(
  apiCall,
  {
    limit: 5,
    window: 60000,
    windowType: 'sliding',
  },
  (state) => ({ rejectionCount: state.rejectionCount })
);

// Opt-in to re-render when execution times change (optimized for window calculations)
const rateLimiter = useRateLimiter(
  apiCall,
  {
    limit: 5,
    window: 60000,
    windowType: 'sliding',
  },
  (state) => ({ executionTimes: state.executionTimes })
);

// Multiple state properties - re-render when any of these change
const rateLimiter = useRateLimiter(
  apiCall,
  {
    limit: 5,
    window: 60000,
    windowType: 'sliding',
  },
  (state) => ({
    executionCount: state.executionCount,
    rejectionCount: state.rejectionCount
  })
);

// Monitor rate limit status
const handleClick = () => {
  const remaining = rateLimiter.getRemainingInWindow();
  if (remaining > 0) {
    rateLimiter.maybeExecute(data);
  } else {
    showRateLimitWarning();
  }
};

// Access the selected state (will be empty object {} unless selector provided)
const { executionCount, rejectionCount } = rateLimiter.state;
我们的合作伙伴
Code Rabbit
Unkey
订阅 Bytes

您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。

Bytes

无垃圾邮件。您可以随时取消订阅。

订阅 Bytes

您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。

Bytes

无垃圾邮件。您可以随时取消订阅。