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

使用速率限制状态

函数: useRateLimitedState()

ts
function useRateLimitedState<TValue, TSelected>(
   value, 
   options, 
   selector?): [TValue, Dispatch<SetStateAction<TValue>>, ReactRateLimiter<Dispatch<SetStateAction<TValue>>, TSelected>]
function useRateLimitedState<TValue, TSelected>(
   value, 
   options, 
   selector?): [TValue, Dispatch<SetStateAction<TValue>>, ReactRateLimiter<Dispatch<SetStateAction<TValue>>, TSelected>]

定义于: react-pacer/src/rate-limiter/useRateLimitedState.ts:107

一个 React hook,用于创建一个速率限制的状态值,对在时间窗口内的状态更新强制执行硬限制。此 hook 结合了 React 的 useState 和速率限制功能,以提供受控的状态更新。

速率限制是一种简单的“硬限制”方法——它允许所有更新直到达到限制,然后阻止后续更新,直到窗口重置。与节流或防抖不同,它不尝试间隔或智能地合并更新。这可能导致快速更新的爆发,随后是无更新的时期。

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

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

为了更平滑的更新模式,请考虑使用

  • useThrottledState:当您希望更新之间有固定的间隔时(例如 UI 更改)
  • useDebouncedState:当您希望将快速更新合并为一次更新时(例如搜索输入)

速率限制主要用于需要强制执行严格限制的情况,例如 API 速率限制。

该 hook 返回一个元组,包含:

  • 速率限制的状态值
  • 一个符合配置限制的速率限制的 setter 函数
  • 用于附加控制的 rateLimiter 实例

为了在没有状态管理的情况下更直接地控制速率限制,请考虑使用更底层的 useRateLimiter hook。

状态管理和选择器

该 hook 使用 TanStack Store 通过底层的 rate limiter 实例进行响应式状态管理。 `selector` 参数允许您指定哪些 rate limiter 状态更改将触发重新渲染,通过防止不相关的状态更改导致的不必要重新渲染来优化性能。

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

可用的速率限制器状态属性

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

类型参数

TValue

TSelected = RateLimiterState

参数

value

TValue

options

RateLimiterOptions<Dispatch<SetStateAction<TValue>>>

选择器?

(state) => TSelected

Returns (返回)

[TValue, Dispatch<SetStateAction<TValue>>, ReactRateLimiter<Dispatch<SetStateAction<TValue>>, TSelected>]

示例

tsx
// Default behavior - no reactive state subscriptions
const [value, setValue, rateLimiter] = useRateLimitedState(0, {
  limit: 5,
  window: 60000,
  windowType: 'sliding'
});

// Opt-in to re-render when execution count changes (optimized for tracking successful updates)
const [value, setValue, rateLimiter] = useRateLimitedState(
  0,
  { 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 [value, setValue, rateLimiter] = useRateLimitedState(
  0,
  { limit: 5, window: 60000, windowType: 'sliding' },
  (state) => ({ rejectionCount: state.rejectionCount })
);

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

// With rejection callback and fixed window
const [value, setValue] = useRateLimitedState(0, {
  limit: 3,
  window: 5000,
  windowType: 'fixed',
  onReject: (rateLimiter) => {
    alert(`Rate limit reached. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
  }
});

// Access rateLimiter methods if needed
const handleSubmit = () => {
  const remaining = rateLimiter.getRemainingInWindow();
  if (remaining > 0) {
    setValue(newValue);
  } else {
    showRateLimitWarning();
  }
};

// Access the selected rate limiter state (will be empty object {} unless selector provided)
const { executionCount, rejectionCount } = rateLimiter.state;
// Default behavior - no reactive state subscriptions
const [value, setValue, rateLimiter] = useRateLimitedState(0, {
  limit: 5,
  window: 60000,
  windowType: 'sliding'
});

// Opt-in to re-render when execution count changes (optimized for tracking successful updates)
const [value, setValue, rateLimiter] = useRateLimitedState(
  0,
  { 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 [value, setValue, rateLimiter] = useRateLimitedState(
  0,
  { limit: 5, window: 60000, windowType: 'sliding' },
  (state) => ({ rejectionCount: state.rejectionCount })
);

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

// With rejection callback and fixed window
const [value, setValue] = useRateLimitedState(0, {
  limit: 3,
  window: 5000,
  windowType: 'fixed',
  onReject: (rateLimiter) => {
    alert(`Rate limit reached. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
  }
});

// Access rateLimiter methods if needed
const handleSubmit = () => {
  const remaining = rateLimiter.getRemainingInWindow();
  if (remaining > 0) {
    setValue(newValue);
  } else {
    showRateLimitWarning();
  }
};

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

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

Bytes

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

订阅 Bytes

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

Bytes

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