@tanstack/preact-pacer 0.0.1 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (274) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +165 -45
  3. package/dist/async-batcher/index.cjs +12 -0
  4. package/dist/async-batcher/index.d.cts +4 -0
  5. package/dist/async-batcher/index.d.ts +4 -0
  6. package/dist/async-batcher/index.js +6 -0
  7. package/dist/async-batcher/useAsyncBatchedCallback.cjs +51 -0
  8. package/dist/async-batcher/useAsyncBatchedCallback.cjs.map +1 -0
  9. package/dist/async-batcher/useAsyncBatchedCallback.d.cts +46 -0
  10. package/dist/async-batcher/useAsyncBatchedCallback.d.ts +46 -0
  11. package/dist/async-batcher/useAsyncBatchedCallback.js +51 -0
  12. package/dist/async-batcher/useAsyncBatchedCallback.js.map +1 -0
  13. package/dist/async-batcher/useAsyncBatcher.cjs +189 -0
  14. package/dist/async-batcher/useAsyncBatcher.cjs.map +1 -0
  15. package/dist/async-batcher/useAsyncBatcher.d.cts +198 -0
  16. package/dist/async-batcher/useAsyncBatcher.d.ts +198 -0
  17. package/dist/async-batcher/useAsyncBatcher.js +189 -0
  18. package/dist/async-batcher/useAsyncBatcher.js.map +1 -0
  19. package/dist/async-debouncer/index.cjs +12 -0
  20. package/dist/async-debouncer/index.d.cts +4 -0
  21. package/dist/async-debouncer/index.d.ts +4 -0
  22. package/dist/async-debouncer/index.js +6 -0
  23. package/dist/async-debouncer/useAsyncDebouncedCallback.cjs +50 -0
  24. package/dist/async-debouncer/useAsyncDebouncedCallback.cjs.map +1 -0
  25. package/dist/async-debouncer/useAsyncDebouncedCallback.d.cts +47 -0
  26. package/dist/async-debouncer/useAsyncDebouncedCallback.d.ts +47 -0
  27. package/dist/async-debouncer/useAsyncDebouncedCallback.js +50 -0
  28. package/dist/async-debouncer/useAsyncDebouncedCallback.js.map +1 -0
  29. package/dist/async-debouncer/useAsyncDebouncer.cjs +173 -0
  30. package/dist/async-debouncer/useAsyncDebouncer.cjs.map +1 -0
  31. package/dist/async-debouncer/useAsyncDebouncer.d.cts +178 -0
  32. package/dist/async-debouncer/useAsyncDebouncer.d.ts +178 -0
  33. package/dist/async-debouncer/useAsyncDebouncer.js +173 -0
  34. package/dist/async-debouncer/useAsyncDebouncer.js.map +1 -0
  35. package/dist/async-queuer/index.cjs +12 -0
  36. package/dist/async-queuer/index.d.cts +4 -0
  37. package/dist/async-queuer/index.d.ts +4 -0
  38. package/dist/async-queuer/index.js +6 -0
  39. package/dist/async-queuer/useAsyncQueuedState.cjs +154 -0
  40. package/dist/async-queuer/useAsyncQueuedState.cjs.map +1 -0
  41. package/dist/async-queuer/useAsyncQueuedState.d.cts +152 -0
  42. package/dist/async-queuer/useAsyncQueuedState.d.ts +152 -0
  43. package/dist/async-queuer/useAsyncQueuedState.js +154 -0
  44. package/dist/async-queuer/useAsyncQueuedState.js.map +1 -0
  45. package/dist/async-queuer/useAsyncQueuer.cjs +189 -0
  46. package/dist/async-queuer/useAsyncQueuer.cjs.map +1 -0
  47. package/dist/async-queuer/useAsyncQueuer.d.cts +198 -0
  48. package/dist/async-queuer/useAsyncQueuer.d.ts +198 -0
  49. package/dist/async-queuer/useAsyncQueuer.js +189 -0
  50. package/dist/async-queuer/useAsyncQueuer.js.map +1 -0
  51. package/dist/async-rate-limiter/index.cjs +12 -0
  52. package/dist/async-rate-limiter/index.d.cts +4 -0
  53. package/dist/async-rate-limiter/index.d.ts +4 -0
  54. package/dist/async-rate-limiter/index.js +6 -0
  55. package/dist/async-rate-limiter/useAsyncRateLimitedCallback.cjs +65 -0
  56. package/dist/async-rate-limiter/useAsyncRateLimitedCallback.cjs.map +1 -0
  57. package/dist/async-rate-limiter/useAsyncRateLimitedCallback.d.cts +62 -0
  58. package/dist/async-rate-limiter/useAsyncRateLimitedCallback.d.ts +62 -0
  59. package/dist/async-rate-limiter/useAsyncRateLimitedCallback.js +65 -0
  60. package/dist/async-rate-limiter/useAsyncRateLimitedCallback.js.map +1 -0
  61. package/dist/async-rate-limiter/useAsyncRateLimiter.cjs +197 -0
  62. package/dist/async-rate-limiter/useAsyncRateLimiter.cjs.map +1 -0
  63. package/dist/async-rate-limiter/useAsyncRateLimiter.d.cts +207 -0
  64. package/dist/async-rate-limiter/useAsyncRateLimiter.d.ts +207 -0
  65. package/dist/async-rate-limiter/useAsyncRateLimiter.js +197 -0
  66. package/dist/async-rate-limiter/useAsyncRateLimiter.js.map +1 -0
  67. package/dist/async-retryer/index.cjs +9 -0
  68. package/dist/async-retryer/index.d.cts +1 -0
  69. package/dist/async-retryer/index.d.ts +1 -0
  70. package/dist/async-retryer/index.js +3 -0
  71. package/dist/async-throttler/index.cjs +12 -0
  72. package/dist/async-throttler/index.d.cts +4 -0
  73. package/dist/async-throttler/index.d.ts +4 -0
  74. package/dist/async-throttler/index.js +6 -0
  75. package/dist/async-throttler/useAsyncThrottledCallback.cjs +48 -0
  76. package/dist/async-throttler/useAsyncThrottledCallback.cjs.map +1 -0
  77. package/dist/async-throttler/useAsyncThrottledCallback.d.cts +45 -0
  78. package/dist/async-throttler/useAsyncThrottledCallback.d.ts +45 -0
  79. package/dist/async-throttler/useAsyncThrottledCallback.js +48 -0
  80. package/dist/async-throttler/useAsyncThrottledCallback.js.map +1 -0
  81. package/dist/async-throttler/useAsyncThrottler.cjs +182 -0
  82. package/dist/async-throttler/useAsyncThrottler.cjs.map +1 -0
  83. package/dist/async-throttler/useAsyncThrottler.d.cts +189 -0
  84. package/dist/async-throttler/useAsyncThrottler.d.ts +189 -0
  85. package/dist/async-throttler/useAsyncThrottler.js +182 -0
  86. package/dist/async-throttler/useAsyncThrottler.js.map +1 -0
  87. package/dist/batcher/index.cjs +12 -0
  88. package/dist/batcher/index.d.cts +4 -0
  89. package/dist/batcher/index.d.ts +4 -0
  90. package/dist/batcher/index.js +6 -0
  91. package/dist/batcher/useBatchedCallback.cjs +47 -0
  92. package/dist/batcher/useBatchedCallback.cjs.map +1 -0
  93. package/dist/batcher/useBatchedCallback.d.cts +44 -0
  94. package/dist/batcher/useBatchedCallback.d.ts +44 -0
  95. package/dist/batcher/useBatchedCallback.js +47 -0
  96. package/dist/batcher/useBatchedCallback.js.map +1 -0
  97. package/dist/batcher/useBatcher.cjs +146 -0
  98. package/dist/batcher/useBatcher.cjs.map +1 -0
  99. package/dist/batcher/useBatcher.d.cts +155 -0
  100. package/dist/batcher/useBatcher.d.ts +155 -0
  101. package/dist/batcher/useBatcher.js +146 -0
  102. package/dist/batcher/useBatcher.js.map +1 -0
  103. package/dist/debouncer/index.cjs +16 -0
  104. package/dist/debouncer/index.d.cts +6 -0
  105. package/dist/debouncer/index.d.ts +6 -0
  106. package/dist/debouncer/index.js +8 -0
  107. package/dist/debouncer/useDebouncedCallback.cjs +48 -0
  108. package/dist/debouncer/useDebouncedCallback.cjs.map +1 -0
  109. package/dist/debouncer/useDebouncedCallback.d.cts +45 -0
  110. package/dist/debouncer/useDebouncedCallback.d.ts +45 -0
  111. package/dist/debouncer/useDebouncedCallback.js +48 -0
  112. package/dist/debouncer/useDebouncedCallback.js.map +1 -0
  113. package/dist/debouncer/useDebouncedState.cjs +89 -0
  114. package/dist/debouncer/useDebouncedState.cjs.map +1 -0
  115. package/dist/debouncer/useDebouncedState.d.cts +82 -0
  116. package/dist/debouncer/useDebouncedState.d.ts +82 -0
  117. package/dist/debouncer/useDebouncedState.js +89 -0
  118. package/dist/debouncer/useDebouncedState.js.map +1 -0
  119. package/dist/debouncer/useDebouncedValue.cjs +96 -0
  120. package/dist/debouncer/useDebouncedValue.cjs.map +1 -0
  121. package/dist/debouncer/useDebouncedValue.d.cts +91 -0
  122. package/dist/debouncer/useDebouncedValue.d.ts +91 -0
  123. package/dist/debouncer/useDebouncedValue.js +96 -0
  124. package/dist/debouncer/useDebouncedValue.js.map +1 -0
  125. package/dist/debouncer/useDebouncer.cjs +128 -0
  126. package/dist/debouncer/useDebouncer.cjs.map +1 -0
  127. package/dist/debouncer/useDebouncer.d.cts +133 -0
  128. package/dist/debouncer/useDebouncer.d.ts +133 -0
  129. package/dist/debouncer/useDebouncer.js +128 -0
  130. package/dist/debouncer/useDebouncer.js.map +1 -0
  131. package/dist/index.cjs +66 -0
  132. package/dist/index.d.cts +30 -0
  133. package/dist/index.d.ts +30 -0
  134. package/dist/index.js +32 -0
  135. package/dist/provider/PacerProvider.cjs +26 -0
  136. package/dist/provider/PacerProvider.cjs.map +1 -0
  137. package/dist/provider/PacerProvider.d.cts +33 -0
  138. package/dist/provider/PacerProvider.d.ts +33 -0
  139. package/dist/provider/PacerProvider.js +24 -0
  140. package/dist/provider/PacerProvider.js.map +1 -0
  141. package/dist/provider/index.cjs +5 -0
  142. package/dist/provider/index.d.cts +2 -0
  143. package/dist/provider/index.d.ts +2 -0
  144. package/dist/provider/index.js +3 -0
  145. package/dist/queuer/index.cjs +14 -0
  146. package/dist/queuer/index.d.cts +5 -0
  147. package/dist/queuer/index.d.ts +5 -0
  148. package/dist/queuer/index.js +7 -0
  149. package/dist/queuer/useQueuedState.cjs +129 -0
  150. package/dist/queuer/useQueuedState.cjs.map +1 -0
  151. package/dist/queuer/useQueuedState.d.cts +123 -0
  152. package/dist/queuer/useQueuedState.d.ts +123 -0
  153. package/dist/queuer/useQueuedState.js +129 -0
  154. package/dist/queuer/useQueuedState.js.map +1 -0
  155. package/dist/queuer/useQueuedValue.cjs +115 -0
  156. package/dist/queuer/useQueuedValue.cjs.map +1 -0
  157. package/dist/queuer/useQueuedValue.d.cts +106 -0
  158. package/dist/queuer/useQueuedValue.d.ts +106 -0
  159. package/dist/queuer/useQueuedValue.js +115 -0
  160. package/dist/queuer/useQueuedValue.js.map +1 -0
  161. package/dist/queuer/useQueuer.cjs +157 -0
  162. package/dist/queuer/useQueuer.cjs.map +1 -0
  163. package/dist/queuer/useQueuer.d.cts +166 -0
  164. package/dist/queuer/useQueuer.d.ts +166 -0
  165. package/dist/queuer/useQueuer.js +157 -0
  166. package/dist/queuer/useQueuer.js.map +1 -0
  167. package/dist/rate-limiter/index.cjs +16 -0
  168. package/dist/rate-limiter/index.d.cts +6 -0
  169. package/dist/rate-limiter/index.d.ts +6 -0
  170. package/dist/rate-limiter/index.js +8 -0
  171. package/dist/rate-limiter/useRateLimitedCallback.cjs +65 -0
  172. package/dist/rate-limiter/useRateLimitedCallback.cjs.map +1 -0
  173. package/dist/rate-limiter/useRateLimitedCallback.d.cts +62 -0
  174. package/dist/rate-limiter/useRateLimitedCallback.d.ts +62 -0
  175. package/dist/rate-limiter/useRateLimitedCallback.js +65 -0
  176. package/dist/rate-limiter/useRateLimitedCallback.js.map +1 -0
  177. package/dist/rate-limiter/useRateLimitedState.cjs +115 -0
  178. package/dist/rate-limiter/useRateLimitedState.cjs.map +1 -0
  179. package/dist/rate-limiter/useRateLimitedState.d.cts +108 -0
  180. package/dist/rate-limiter/useRateLimitedState.d.ts +108 -0
  181. package/dist/rate-limiter/useRateLimitedState.js +115 -0
  182. package/dist/rate-limiter/useRateLimitedState.js.map +1 -0
  183. package/dist/rate-limiter/useRateLimitedValue.cjs +102 -0
  184. package/dist/rate-limiter/useRateLimitedValue.cjs.map +1 -0
  185. package/dist/rate-limiter/useRateLimitedValue.d.cts +97 -0
  186. package/dist/rate-limiter/useRateLimitedValue.d.ts +97 -0
  187. package/dist/rate-limiter/useRateLimitedValue.js +102 -0
  188. package/dist/rate-limiter/useRateLimitedValue.js.map +1 -0
  189. package/dist/rate-limiter/useRateLimiter.cjs +162 -0
  190. package/dist/rate-limiter/useRateLimiter.cjs.map +1 -0
  191. package/dist/rate-limiter/useRateLimiter.d.cts +172 -0
  192. package/dist/rate-limiter/useRateLimiter.d.ts +172 -0
  193. package/dist/rate-limiter/useRateLimiter.js +162 -0
  194. package/dist/rate-limiter/useRateLimiter.js.map +1 -0
  195. package/dist/throttler/index.cjs +16 -0
  196. package/dist/throttler/index.d.cts +6 -0
  197. package/dist/throttler/index.d.ts +6 -0
  198. package/dist/throttler/index.js +8 -0
  199. package/dist/throttler/useThrottledCallback.cjs +49 -0
  200. package/dist/throttler/useThrottledCallback.cjs.map +1 -0
  201. package/dist/throttler/useThrottledCallback.d.cts +46 -0
  202. package/dist/throttler/useThrottledCallback.d.ts +46 -0
  203. package/dist/throttler/useThrottledCallback.js +49 -0
  204. package/dist/throttler/useThrottledCallback.js.map +1 -0
  205. package/dist/throttler/useThrottledState.cjs +100 -0
  206. package/dist/throttler/useThrottledState.cjs.map +1 -0
  207. package/dist/throttler/useThrottledState.d.cts +93 -0
  208. package/dist/throttler/useThrottledState.d.ts +93 -0
  209. package/dist/throttler/useThrottledState.js +100 -0
  210. package/dist/throttler/useThrottledState.js.map +1 -0
  211. package/dist/throttler/useThrottledValue.cjs +91 -0
  212. package/dist/throttler/useThrottledValue.cjs.map +1 -0
  213. package/dist/throttler/useThrottledValue.d.cts +86 -0
  214. package/dist/throttler/useThrottledValue.d.ts +86 -0
  215. package/dist/throttler/useThrottledValue.js +91 -0
  216. package/dist/throttler/useThrottledValue.js.map +1 -0
  217. package/dist/throttler/useThrottler.cjs +133 -0
  218. package/dist/throttler/useThrottler.cjs.map +1 -0
  219. package/dist/throttler/useThrottler.d.cts +138 -0
  220. package/dist/throttler/useThrottler.d.ts +138 -0
  221. package/dist/throttler/useThrottler.js +133 -0
  222. package/dist/throttler/useThrottler.js.map +1 -0
  223. package/dist/types/index.cjs +9 -0
  224. package/dist/types/index.d.cts +1 -0
  225. package/dist/types/index.d.ts +1 -0
  226. package/dist/types/index.js +3 -0
  227. package/dist/utils/index.cjs +9 -0
  228. package/dist/utils/index.d.cts +1 -0
  229. package/dist/utils/index.d.ts +1 -0
  230. package/dist/utils/index.js +3 -0
  231. package/package.json +118 -7
  232. package/src/async-batcher/index.ts +4 -0
  233. package/src/async-batcher/useAsyncBatchedCallback.ts +54 -0
  234. package/src/async-batcher/useAsyncBatcher.ts +249 -0
  235. package/src/async-debouncer/index.ts +5 -0
  236. package/src/async-debouncer/useAsyncDebouncedCallback.ts +54 -0
  237. package/src/async-debouncer/useAsyncDebouncer.ts +235 -0
  238. package/src/async-queuer/index.ts +4 -0
  239. package/src/async-queuer/useAsyncQueuedState.ts +165 -0
  240. package/src/async-queuer/useAsyncQueuer.ts +249 -0
  241. package/src/async-rate-limiter/index.ts +5 -0
  242. package/src/async-rate-limiter/useAsyncRateLimitedCallback.ts +69 -0
  243. package/src/async-rate-limiter/useAsyncRateLimiter.ts +261 -0
  244. package/src/async-retryer/index.ts +2 -0
  245. package/src/async-throttler/index.ts +5 -0
  246. package/src/async-throttler/useAsyncThrottledCallback.ts +52 -0
  247. package/src/async-throttler/useAsyncThrottler.ts +244 -0
  248. package/src/batcher/index.ts +4 -0
  249. package/src/batcher/useBatchedCallback.ts +50 -0
  250. package/src/batcher/useBatcher.ts +203 -0
  251. package/src/debouncer/index.ts +7 -0
  252. package/src/debouncer/useDebouncedCallback.ts +51 -0
  253. package/src/debouncer/useDebouncedState.ts +109 -0
  254. package/src/debouncer/useDebouncedValue.ts +112 -0
  255. package/src/debouncer/useDebouncer.ts +189 -0
  256. package/src/index.ts +56 -0
  257. package/src/provider/PacerProvider.tsx +70 -0
  258. package/src/provider/index.ts +1 -0
  259. package/src/queuer/index.ts +5 -0
  260. package/src/queuer/useQueuedState.ts +133 -0
  261. package/src/queuer/useQueuedValue.ts +129 -0
  262. package/src/queuer/useQueuer.ts +213 -0
  263. package/src/rate-limiter/index.ts +6 -0
  264. package/src/rate-limiter/useRateLimitedCallback.ts +68 -0
  265. package/src/rate-limiter/useRateLimitedState.ts +124 -0
  266. package/src/rate-limiter/useRateLimitedValue.ts +110 -0
  267. package/src/rate-limiter/useRateLimiter.ts +222 -0
  268. package/src/throttler/index.ts +7 -0
  269. package/src/throttler/useThrottledCallback.ts +52 -0
  270. package/src/throttler/useThrottledState.ts +121 -0
  271. package/src/throttler/useThrottledValue.ts +107 -0
  272. package/src/throttler/useThrottler.ts +194 -0
  273. package/src/types/index.ts +1 -0
  274. package/src/utils/index.ts +1 -0
@@ -0,0 +1,222 @@
1
+ import { useMemo, useState } from 'preact/hooks'
2
+ import { RateLimiter } from '@tanstack/pacer/rate-limiter'
3
+ import { useStore } from '@tanstack/preact-store'
4
+ import { useDefaultPacerOptions } from '../provider/PacerProvider'
5
+ import type { Store } from '@tanstack/preact-store'
6
+ import type {
7
+ RateLimiterOptions,
8
+ RateLimiterState,
9
+ } from '@tanstack/pacer/rate-limiter'
10
+ import type { AnyFunction } from '@tanstack/pacer/types'
11
+ import type { ComponentChildren } from 'preact'
12
+
13
+ export interface PreactRateLimiter<
14
+ TFn extends AnyFunction,
15
+ TSelected = {},
16
+ > extends Omit<RateLimiter<TFn>, 'store'> {
17
+ /**
18
+ * A Preact HOC (Higher Order Component) that allows you to subscribe to the rate limiter state.
19
+ *
20
+ * This is useful for opting into state re-renders for specific parts of the rate limiter state
21
+ * deep in your component tree without needing to pass a selector to the hook.
22
+ *
23
+ * @example
24
+ * <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>
25
+ * {({ rejectionCount }) => (
26
+ * <div>Rejections: {rejectionCount}</div>
27
+ * )}
28
+ * </rateLimiter.Subscribe>
29
+ */
30
+ Subscribe: <TSelected>(props: {
31
+ selector: (state: RateLimiterState) => TSelected
32
+ children: ((state: TSelected) => ComponentChildren) | ComponentChildren
33
+ }) => ComponentChildren
34
+ /**
35
+ * Reactive state that will be updated and re-rendered when the rate limiter state changes
36
+ *
37
+ * Use this instead of `rateLimiter.store.state`
38
+ */
39
+ readonly state: Readonly<TSelected>
40
+ /**
41
+ * @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state.
42
+ * The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.
43
+ * Although, you can make the state reactive by using the `useStore` in your own usage.
44
+ */
45
+ readonly store: Store<Readonly<RateLimiterState>>
46
+ }
47
+
48
+ /**
49
+ * A low-level Preact hook that creates a `RateLimiter` instance to enforce rate limits on function execution.
50
+ *
51
+ * This hook is designed to be flexible and state-management agnostic - it simply returns a rate limiter instance that
52
+ * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).
53
+ *
54
+ * Rate limiting is a simple "hard limit" approach that allows executions until a maximum count is reached within
55
+ * a time window, then blocks all subsequent calls until the window resets. Unlike throttling or debouncing,
56
+ * it does not attempt to space out or collapse executions intelligently.
57
+ *
58
+ * The rate limiter supports two types of windows:
59
+ * - 'fixed': A strict window that resets after the window period. All executions within the window count
60
+ * towards the limit, and the window resets completely after the period.
61
+ * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
62
+ * consistent rate of execution over time.
63
+ *
64
+ * For smoother execution patterns:
65
+ * - Use throttling when you want consistent spacing between executions (e.g. UI updates)
66
+ * - Use debouncing when you want to collapse rapid-fire events (e.g. search input)
67
+ * - Use rate limiting only when you need to enforce hard limits (e.g. API rate limits)
68
+ *
69
+ * ## State Management and Selector
70
+ *
71
+ * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
72
+ * in two ways:
73
+ *
74
+ * **1. Using `rateLimiter.Subscribe` HOC (Recommended for component tree subscriptions)**
75
+ *
76
+ * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
77
+ * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
78
+ * in child components.
79
+ *
80
+ * **2. Using the `selector` parameter (For hook-level subscriptions)**
81
+ *
82
+ * The `selector` parameter allows you to specify which state changes will trigger a re-render
83
+ * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
84
+ * state changes occur.
85
+ *
86
+ * **By default, there will be no reactive state subscriptions** and you must opt-in to state
87
+ * tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
88
+ * re-renders and gives you full control over when your component updates.
89
+ *
90
+ * Available state properties:
91
+ * - `executionCount`: Number of function executions that have been completed
92
+ * - `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations
93
+ * - `rejectionCount`: Number of function executions that have been rejected due to rate limiting
94
+ *
95
+ * The hook returns an object containing:
96
+ * - maybeExecute: The rate-limited function that respects the configured limits
97
+ * - getExecutionCount: Returns the number of successful executions
98
+ * - getRejectionCount: Returns the number of rejected executions due to rate limiting
99
+ * - getRemainingInWindow: Returns how many more executions are allowed in the current window
100
+ * - reset: Resets the execution counts and window timing
101
+ *
102
+ * @example
103
+ * ```tsx
104
+ * // Default behavior - no reactive state subscriptions
105
+ * const rateLimiter = useRateLimiter(apiCall, {
106
+ * limit: 5,
107
+ * window: 60000,
108
+ * windowType: 'sliding',
109
+ * });
110
+ *
111
+ * // Subscribe to state changes deep in component tree using Subscribe HOC
112
+ * <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>
113
+ * {({ rejectionCount }) => (
114
+ * <div>Rejections: {rejectionCount}</div>
115
+ * )}
116
+ * </rateLimiter.Subscribe>
117
+ *
118
+ * // Opt-in to re-render when execution count changes at hook level (optimized for tracking successful executions)
119
+ * const rateLimiter = useRateLimiter(
120
+ * apiCall,
121
+ * {
122
+ * limit: 5,
123
+ * window: 60000,
124
+ * windowType: 'sliding',
125
+ * },
126
+ * (state) => ({ executionCount: state.executionCount })
127
+ * );
128
+ *
129
+ * // Opt-in to re-render when rejection count changes (optimized for tracking rate limit violations)
130
+ * const rateLimiter = useRateLimiter(
131
+ * apiCall,
132
+ * {
133
+ * limit: 5,
134
+ * window: 60000,
135
+ * windowType: 'sliding',
136
+ * },
137
+ * (state) => ({ rejectionCount: state.rejectionCount })
138
+ * );
139
+ *
140
+ * // Opt-in to re-render when execution times change (optimized for window calculations)
141
+ * const rateLimiter = useRateLimiter(
142
+ * apiCall,
143
+ * {
144
+ * limit: 5,
145
+ * window: 60000,
146
+ * windowType: 'sliding',
147
+ * },
148
+ * (state) => ({ executionTimes: state.executionTimes })
149
+ * );
150
+ *
151
+ * // Multiple state properties - re-render when any of these change
152
+ * const rateLimiter = useRateLimiter(
153
+ * apiCall,
154
+ * {
155
+ * limit: 5,
156
+ * window: 60000,
157
+ * windowType: 'sliding',
158
+ * },
159
+ * (state) => ({
160
+ * executionCount: state.executionCount,
161
+ * rejectionCount: state.rejectionCount
162
+ * })
163
+ * );
164
+ *
165
+ * // Monitor rate limit status
166
+ * const handleClick = () => {
167
+ * const remaining = rateLimiter.getRemainingInWindow();
168
+ * if (remaining > 0) {
169
+ * rateLimiter.maybeExecute(data);
170
+ * } else {
171
+ * showRateLimitWarning();
172
+ * }
173
+ * };
174
+ *
175
+ * // Access the selected state (will be empty object {} unless selector provided)
176
+ * const { executionCount, rejectionCount } = rateLimiter.state;
177
+ * ```
178
+ */
179
+ export function useRateLimiter<TFn extends AnyFunction, TSelected = {}>(
180
+ fn: TFn,
181
+ options: RateLimiterOptions<TFn>,
182
+ selector: (state: RateLimiterState) => TSelected = () => ({}) as TSelected,
183
+ ): PreactRateLimiter<TFn, TSelected> {
184
+ const mergedOptions = {
185
+ ...useDefaultPacerOptions().rateLimiter,
186
+ ...options,
187
+ } as RateLimiterOptions<TFn>
188
+
189
+ const [rateLimiter] = useState(() => {
190
+ const rateLimiterInstance = new RateLimiter<TFn>(
191
+ fn,
192
+ mergedOptions,
193
+ ) as unknown as PreactRateLimiter<TFn, TSelected>
194
+
195
+ rateLimiterInstance.Subscribe = function Subscribe<TSelected>(props: {
196
+ selector: (state: RateLimiterState) => TSelected
197
+ children: ((state: TSelected) => ComponentChildren) | ComponentChildren
198
+ }) {
199
+ const selected = useStore(rateLimiterInstance.store, props.selector)
200
+
201
+ return typeof props.children === 'function'
202
+ ? props.children(selected)
203
+ : props.children
204
+ }
205
+
206
+ return rateLimiterInstance
207
+ })
208
+
209
+ rateLimiter.fn = fn
210
+ rateLimiter.setOptions(mergedOptions)
211
+
212
+ const state = useStore(rateLimiter.store, selector)
213
+
214
+ return useMemo(
215
+ () =>
216
+ ({
217
+ ...rateLimiter,
218
+ state,
219
+ }) as PreactRateLimiter<TFn, TSelected>, // omit `store` in favor of `state`
220
+ [rateLimiter, state],
221
+ )
222
+ }
@@ -0,0 +1,7 @@
1
+ // re-export everything from the core pacer package, BUT ONLY from the throttler module
2
+ export * from '@tanstack/pacer/throttler'
3
+
4
+ export * from './useThrottledCallback'
5
+ export * from './useThrottledState'
6
+ export * from './useThrottledValue'
7
+ export * from './useThrottler'
@@ -0,0 +1,52 @@
1
+ import { useCallback } from 'preact/hooks'
2
+ import { useThrottler } from './useThrottler'
3
+ import type { ThrottlerOptions } from '@tanstack/pacer/throttler'
4
+ import type { AnyFunction } from '@tanstack/pacer/types'
5
+
6
+ /**
7
+ * A Preact hook that creates a throttled version of a callback function.
8
+ * This hook is essentially a wrapper around the basic `throttle` function
9
+ * that is exported from `@tanstack/pacer`,
10
+ * but optimized for Preact with reactive options and a stable function reference.
11
+ *
12
+ * The throttled function will execute at most once within the specified wait time period,
13
+ * regardless of how many times it is called. If called multiple times during the wait period,
14
+ * only the first invocation will execute, and subsequent calls will be ignored until
15
+ * the wait period has elapsed.
16
+ *
17
+ * This hook provides a simpler API compared to `useThrottler`, making it ideal for basic
18
+ * throttling needs. However, it does not expose the underlying Throttler instance.
19
+ *
20
+ * For advanced usage requiring features like:
21
+ * - Manual cancellation
22
+ * - Access to execution counts
23
+ * - Custom useCallback dependencies
24
+ *
25
+ * Consider using the `useThrottler` hook instead.
26
+ *
27
+ * @example
28
+ * ```tsx
29
+ * // Throttle a window resize handler
30
+ * const handleResize = useThrottledCallback(() => {
31
+ * updateLayoutMeasurements();
32
+ * }, {
33
+ * wait: 100 // Execute at most once every 100ms
34
+ * });
35
+ *
36
+ * // Use in an event listener
37
+ * useEffect(() => {
38
+ * window.addEventListener('resize', handleResize);
39
+ * return () => window.removeEventListener('resize', handleResize);
40
+ * }, [handleResize]);
41
+ * ```
42
+ */
43
+ export function useThrottledCallback<TFn extends AnyFunction>(
44
+ fn: TFn,
45
+ options: ThrottlerOptions<TFn>,
46
+ ): (...args: Parameters<TFn>) => void {
47
+ const throttledFn = useThrottler(fn, options).maybeExecute
48
+ return useCallback(
49
+ (...args: Parameters<TFn>) => throttledFn(...args),
50
+ [throttledFn],
51
+ )
52
+ }
@@ -0,0 +1,121 @@
1
+ import { useState } from 'preact/hooks'
2
+ import { useThrottler } from './useThrottler'
3
+ import type { Dispatch, StateUpdater } from 'preact/hooks'
4
+ import type { PreactThrottler } from './useThrottler'
5
+ import type {
6
+ ThrottlerOptions,
7
+ ThrottlerState,
8
+ } from '@tanstack/pacer/throttler'
9
+
10
+ /**
11
+ * A Preact hook that creates a throttled state value that updates at most once within a specified time window.
12
+ * This hook combines Preact's useState with throttling functionality to provide controlled state updates.
13
+ *
14
+ * Throttling ensures state updates occur at a controlled rate regardless of how frequently the setter is called.
15
+ * This is useful for rate-limiting expensive re-renders or operations that depend on rapidly changing state.
16
+ *
17
+ * The hook returns a tuple containing:
18
+ * - The throttled state value
19
+ * - A throttled setter function that respects the configured wait time
20
+ * - The throttler instance for additional control
21
+ *
22
+ * For more direct control over throttling without state management,
23
+ * consider using the lower-level useThrottler hook instead.
24
+ *
25
+ * ## State Management and Selector
26
+ *
27
+ * The hook uses TanStack Store for reactive state management via the underlying throttler instance.
28
+ * The `selector` parameter allows you to specify which throttler state changes will trigger a re-render,
29
+ * optimizing performance by preventing unnecessary re-renders when irrelevant state changes occur.
30
+ *
31
+ * **By default, there will be no reactive state subscriptions** and you must opt-in to state
32
+ * tracking by providing a selector function. This prevents unnecessary re-renders and gives you
33
+ * full control over when your component updates. Only when you provide a selector will the
34
+ * component re-render when the selected state values change.
35
+ *
36
+ * Available throttler state properties:
37
+ * - `executionCount`: Number of function executions that have been completed
38
+ * - `lastArgs`: The arguments from the most recent call to maybeExecute
39
+ * - `lastExecutionTime`: Timestamp of the last function execution in milliseconds
40
+ * - `nextExecutionTime`: Timestamp when the next execution can occur in milliseconds
41
+ * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution
42
+ * - `status`: Current execution status ('disabled' | 'idle' | 'pending')
43
+ *
44
+ * @example
45
+ * ```tsx
46
+ * // Default behavior - no reactive state subscriptions
47
+ * const [value, setValue, throttler] = useThrottledState(0, { wait: 1000 });
48
+ *
49
+ * // Opt-in to re-render when execution count changes (optimized for tracking executions)
50
+ * const [value, setValue, throttler] = useThrottledState(
51
+ * 0,
52
+ * { wait: 1000 },
53
+ * (state) => ({ executionCount: state.executionCount })
54
+ * );
55
+ *
56
+ * // Opt-in to re-render when throttling state changes (optimized for loading indicators)
57
+ * const [value, setValue, throttler] = useThrottledState(
58
+ * 0,
59
+ * { wait: 1000 },
60
+ * (state) => ({
61
+ * isPending: state.isPending,
62
+ * status: state.status
63
+ * })
64
+ * );
65
+ *
66
+ * // Opt-in to re-render when timing information changes (optimized for timing displays)
67
+ * const [value, setValue, throttler] = useThrottledState(
68
+ * 0,
69
+ * { wait: 1000 },
70
+ * (state) => ({
71
+ * lastExecutionTime: state.lastExecutionTime,
72
+ * nextExecutionTime: state.nextExecutionTime
73
+ * })
74
+ * );
75
+ *
76
+ * // With custom leading/trailing behavior
77
+ * const [value, setValue] = useThrottledState(0, {
78
+ * wait: 1000,
79
+ * leading: true, // Update immediately on first change
80
+ * trailing: false // Skip trailing edge updates
81
+ * });
82
+ *
83
+ * // Access throttler methods if needed
84
+ * const handleReset = () => {
85
+ * setValue(0);
86
+ * throttler.cancel(); // Cancel any pending updates
87
+ * };
88
+ *
89
+ * // Access the selected throttler state (will be empty object {} unless selector provided)
90
+ * const { executionCount, isPending } = throttler.state;
91
+ * ```
92
+ */
93
+
94
+ export function useThrottledState<
95
+ TValue,
96
+ TSelected = ThrottlerState<Dispatch<StateUpdater<TValue>>>,
97
+ >(
98
+ value: TValue,
99
+ options: ThrottlerOptions<Dispatch<StateUpdater<TValue>>>,
100
+ selector?: (
101
+ state: ThrottlerState<Dispatch<StateUpdater<TValue>>>,
102
+ ) => TSelected,
103
+ ): [
104
+ TValue,
105
+ Dispatch<StateUpdater<TValue>>,
106
+ PreactThrottler<Dispatch<StateUpdater<TValue>>, TSelected>,
107
+ ] {
108
+ const [throttledValue, setThrottledValue] = useState<TValue>(value)
109
+ const throttler = useThrottler(
110
+ setThrottledValue,
111
+ options,
112
+ selector as (
113
+ state: ThrottlerState<Dispatch<StateUpdater<TValue>>>,
114
+ ) => TSelected,
115
+ )
116
+ return [
117
+ throttledValue,
118
+ throttler.maybeExecute as Dispatch<StateUpdater<TValue>>,
119
+ throttler,
120
+ ]
121
+ }
@@ -0,0 +1,107 @@
1
+ import { useEffect } from 'preact/hooks'
2
+ import { useThrottledState } from './useThrottledState'
3
+ import type { Dispatch, StateUpdater } from 'preact/hooks'
4
+ import type { PreactThrottler } from './useThrottler'
5
+ import type {
6
+ ThrottlerOptions,
7
+ ThrottlerState,
8
+ } from '@tanstack/pacer/throttler'
9
+
10
+ /**
11
+ * A high-level Preact hook that creates a throttled version of a value that updates at most once within a specified time window.
12
+ * This hook uses Preact's useState internally to manage the throttled state.
13
+ *
14
+ * Throttling ensures the value updates occur at a controlled rate regardless of how frequently the input value changes.
15
+ * This is useful for rate-limiting expensive re-renders or API calls that depend on rapidly changing values.
16
+ *
17
+ * The hook returns a tuple containing:
18
+ * - The throttled value that updates according to the leading/trailing edge behavior specified in the options
19
+ * - The throttler instance with control methods
20
+ *
21
+ * For more direct control over throttling behavior without Preact state management,
22
+ * consider using the lower-level useThrottler hook instead.
23
+ *
24
+ * ## State Management and Selector
25
+ *
26
+ * The hook uses TanStack Store for reactive state management via the underlying throttler instance.
27
+ * The `selector` parameter allows you to specify which throttler state changes will trigger a re-render,
28
+ * optimizing performance by preventing unnecessary re-renders when irrelevant state changes occur.
29
+ *
30
+ * **By default, there will be no reactive state subscriptions** and you must opt-in to state
31
+ * tracking by providing a selector function. This prevents unnecessary re-renders and gives you
32
+ * full control over when your component updates. Only when you provide a selector will the
33
+ * component re-render when the selected state values change.
34
+ *
35
+ * Available throttler state properties:
36
+ * - `executionCount`: Number of function executions that have been completed
37
+ * - `lastArgs`: The arguments from the most recent call to maybeExecute
38
+ * - `lastExecutionTime`: Timestamp of the last function execution in milliseconds
39
+ * - `nextExecutionTime`: Timestamp when the next execution can occur in milliseconds
40
+ * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution
41
+ * - `status`: Current execution status ('disabled' | 'idle' | 'pending')
42
+ *
43
+ * @example
44
+ * ```tsx
45
+ * // Default behavior - no reactive state subscriptions
46
+ * const [throttledValue, throttler] = useThrottledValue(rawValue, { wait: 1000 });
47
+ *
48
+ * // Opt-in to re-render when execution count changes (optimized for tracking executions)
49
+ * const [throttledValue, throttler] = useThrottledValue(
50
+ * rawValue,
51
+ * { wait: 1000 },
52
+ * (state) => ({ executionCount: state.executionCount })
53
+ * );
54
+ *
55
+ * // Opt-in to re-render when throttling state changes (optimized for loading indicators)
56
+ * const [throttledValue, throttler] = useThrottledValue(
57
+ * rawValue,
58
+ * { wait: 1000 },
59
+ * (state) => ({
60
+ * isPending: state.isPending,
61
+ * status: state.status
62
+ * })
63
+ * );
64
+ *
65
+ * // Opt-in to re-render when timing information changes (optimized for timing displays)
66
+ * const [throttledValue, throttler] = useThrottledValue(
67
+ * rawValue,
68
+ * { wait: 1000 },
69
+ * (state) => ({
70
+ * lastExecutionTime: state.lastExecutionTime,
71
+ * nextExecutionTime: state.nextExecutionTime
72
+ * })
73
+ * );
74
+ *
75
+ * // With custom leading/trailing behavior
76
+ * const [throttledValue, throttler] = useThrottledValue(rawValue, {
77
+ * wait: 1000,
78
+ * leading: true, // Update immediately on first change
79
+ * trailing: false // Skip trailing edge updates
80
+ * });
81
+ *
82
+ * // Access the selected throttler state (will be empty object {} unless selector provided)
83
+ * const { executionCount, isPending } = throttler.state;
84
+ * ```
85
+ */
86
+ export function useThrottledValue<
87
+ TValue,
88
+ TSelected = ThrottlerState<Dispatch<StateUpdater<TValue>>>,
89
+ >(
90
+ value: TValue,
91
+ options: ThrottlerOptions<Dispatch<StateUpdater<TValue>>>,
92
+ selector?: (
93
+ state: ThrottlerState<Dispatch<StateUpdater<TValue>>>,
94
+ ) => TSelected,
95
+ ): [TValue, PreactThrottler<Dispatch<StateUpdater<TValue>>, TSelected>] {
96
+ const [throttledValue, setThrottledValue, throttler] = useThrottledState(
97
+ value,
98
+ options,
99
+ selector,
100
+ )
101
+
102
+ useEffect(() => {
103
+ ;(setThrottledValue as (value: TValue) => void)(value)
104
+ }, [value, setThrottledValue])
105
+
106
+ return [throttledValue, throttler]
107
+ }