@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.
- package/LICENSE +21 -0
- package/README.md +165 -45
- package/dist/async-batcher/index.cjs +12 -0
- package/dist/async-batcher/index.d.cts +4 -0
- package/dist/async-batcher/index.d.ts +4 -0
- package/dist/async-batcher/index.js +6 -0
- package/dist/async-batcher/useAsyncBatchedCallback.cjs +51 -0
- package/dist/async-batcher/useAsyncBatchedCallback.cjs.map +1 -0
- package/dist/async-batcher/useAsyncBatchedCallback.d.cts +46 -0
- package/dist/async-batcher/useAsyncBatchedCallback.d.ts +46 -0
- package/dist/async-batcher/useAsyncBatchedCallback.js +51 -0
- package/dist/async-batcher/useAsyncBatchedCallback.js.map +1 -0
- package/dist/async-batcher/useAsyncBatcher.cjs +189 -0
- package/dist/async-batcher/useAsyncBatcher.cjs.map +1 -0
- package/dist/async-batcher/useAsyncBatcher.d.cts +198 -0
- package/dist/async-batcher/useAsyncBatcher.d.ts +198 -0
- package/dist/async-batcher/useAsyncBatcher.js +189 -0
- package/dist/async-batcher/useAsyncBatcher.js.map +1 -0
- package/dist/async-debouncer/index.cjs +12 -0
- package/dist/async-debouncer/index.d.cts +4 -0
- package/dist/async-debouncer/index.d.ts +4 -0
- package/dist/async-debouncer/index.js +6 -0
- package/dist/async-debouncer/useAsyncDebouncedCallback.cjs +50 -0
- package/dist/async-debouncer/useAsyncDebouncedCallback.cjs.map +1 -0
- package/dist/async-debouncer/useAsyncDebouncedCallback.d.cts +47 -0
- package/dist/async-debouncer/useAsyncDebouncedCallback.d.ts +47 -0
- package/dist/async-debouncer/useAsyncDebouncedCallback.js +50 -0
- package/dist/async-debouncer/useAsyncDebouncedCallback.js.map +1 -0
- package/dist/async-debouncer/useAsyncDebouncer.cjs +173 -0
- package/dist/async-debouncer/useAsyncDebouncer.cjs.map +1 -0
- package/dist/async-debouncer/useAsyncDebouncer.d.cts +178 -0
- package/dist/async-debouncer/useAsyncDebouncer.d.ts +178 -0
- package/dist/async-debouncer/useAsyncDebouncer.js +173 -0
- package/dist/async-debouncer/useAsyncDebouncer.js.map +1 -0
- package/dist/async-queuer/index.cjs +12 -0
- package/dist/async-queuer/index.d.cts +4 -0
- package/dist/async-queuer/index.d.ts +4 -0
- package/dist/async-queuer/index.js +6 -0
- package/dist/async-queuer/useAsyncQueuedState.cjs +154 -0
- package/dist/async-queuer/useAsyncQueuedState.cjs.map +1 -0
- package/dist/async-queuer/useAsyncQueuedState.d.cts +152 -0
- package/dist/async-queuer/useAsyncQueuedState.d.ts +152 -0
- package/dist/async-queuer/useAsyncQueuedState.js +154 -0
- package/dist/async-queuer/useAsyncQueuedState.js.map +1 -0
- package/dist/async-queuer/useAsyncQueuer.cjs +189 -0
- package/dist/async-queuer/useAsyncQueuer.cjs.map +1 -0
- package/dist/async-queuer/useAsyncQueuer.d.cts +198 -0
- package/dist/async-queuer/useAsyncQueuer.d.ts +198 -0
- package/dist/async-queuer/useAsyncQueuer.js +189 -0
- package/dist/async-queuer/useAsyncQueuer.js.map +1 -0
- package/dist/async-rate-limiter/index.cjs +12 -0
- package/dist/async-rate-limiter/index.d.cts +4 -0
- package/dist/async-rate-limiter/index.d.ts +4 -0
- package/dist/async-rate-limiter/index.js +6 -0
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.cjs +65 -0
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.cjs.map +1 -0
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.d.cts +62 -0
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.d.ts +62 -0
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.js +65 -0
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.js.map +1 -0
- package/dist/async-rate-limiter/useAsyncRateLimiter.cjs +197 -0
- package/dist/async-rate-limiter/useAsyncRateLimiter.cjs.map +1 -0
- package/dist/async-rate-limiter/useAsyncRateLimiter.d.cts +207 -0
- package/dist/async-rate-limiter/useAsyncRateLimiter.d.ts +207 -0
- package/dist/async-rate-limiter/useAsyncRateLimiter.js +197 -0
- package/dist/async-rate-limiter/useAsyncRateLimiter.js.map +1 -0
- package/dist/async-retryer/index.cjs +9 -0
- package/dist/async-retryer/index.d.cts +1 -0
- package/dist/async-retryer/index.d.ts +1 -0
- package/dist/async-retryer/index.js +3 -0
- package/dist/async-throttler/index.cjs +12 -0
- package/dist/async-throttler/index.d.cts +4 -0
- package/dist/async-throttler/index.d.ts +4 -0
- package/dist/async-throttler/index.js +6 -0
- package/dist/async-throttler/useAsyncThrottledCallback.cjs +48 -0
- package/dist/async-throttler/useAsyncThrottledCallback.cjs.map +1 -0
- package/dist/async-throttler/useAsyncThrottledCallback.d.cts +45 -0
- package/dist/async-throttler/useAsyncThrottledCallback.d.ts +45 -0
- package/dist/async-throttler/useAsyncThrottledCallback.js +48 -0
- package/dist/async-throttler/useAsyncThrottledCallback.js.map +1 -0
- package/dist/async-throttler/useAsyncThrottler.cjs +182 -0
- package/dist/async-throttler/useAsyncThrottler.cjs.map +1 -0
- package/dist/async-throttler/useAsyncThrottler.d.cts +189 -0
- package/dist/async-throttler/useAsyncThrottler.d.ts +189 -0
- package/dist/async-throttler/useAsyncThrottler.js +182 -0
- package/dist/async-throttler/useAsyncThrottler.js.map +1 -0
- package/dist/batcher/index.cjs +12 -0
- package/dist/batcher/index.d.cts +4 -0
- package/dist/batcher/index.d.ts +4 -0
- package/dist/batcher/index.js +6 -0
- package/dist/batcher/useBatchedCallback.cjs +47 -0
- package/dist/batcher/useBatchedCallback.cjs.map +1 -0
- package/dist/batcher/useBatchedCallback.d.cts +44 -0
- package/dist/batcher/useBatchedCallback.d.ts +44 -0
- package/dist/batcher/useBatchedCallback.js +47 -0
- package/dist/batcher/useBatchedCallback.js.map +1 -0
- package/dist/batcher/useBatcher.cjs +146 -0
- package/dist/batcher/useBatcher.cjs.map +1 -0
- package/dist/batcher/useBatcher.d.cts +155 -0
- package/dist/batcher/useBatcher.d.ts +155 -0
- package/dist/batcher/useBatcher.js +146 -0
- package/dist/batcher/useBatcher.js.map +1 -0
- package/dist/debouncer/index.cjs +16 -0
- package/dist/debouncer/index.d.cts +6 -0
- package/dist/debouncer/index.d.ts +6 -0
- package/dist/debouncer/index.js +8 -0
- package/dist/debouncer/useDebouncedCallback.cjs +48 -0
- package/dist/debouncer/useDebouncedCallback.cjs.map +1 -0
- package/dist/debouncer/useDebouncedCallback.d.cts +45 -0
- package/dist/debouncer/useDebouncedCallback.d.ts +45 -0
- package/dist/debouncer/useDebouncedCallback.js +48 -0
- package/dist/debouncer/useDebouncedCallback.js.map +1 -0
- package/dist/debouncer/useDebouncedState.cjs +89 -0
- package/dist/debouncer/useDebouncedState.cjs.map +1 -0
- package/dist/debouncer/useDebouncedState.d.cts +82 -0
- package/dist/debouncer/useDebouncedState.d.ts +82 -0
- package/dist/debouncer/useDebouncedState.js +89 -0
- package/dist/debouncer/useDebouncedState.js.map +1 -0
- package/dist/debouncer/useDebouncedValue.cjs +96 -0
- package/dist/debouncer/useDebouncedValue.cjs.map +1 -0
- package/dist/debouncer/useDebouncedValue.d.cts +91 -0
- package/dist/debouncer/useDebouncedValue.d.ts +91 -0
- package/dist/debouncer/useDebouncedValue.js +96 -0
- package/dist/debouncer/useDebouncedValue.js.map +1 -0
- package/dist/debouncer/useDebouncer.cjs +128 -0
- package/dist/debouncer/useDebouncer.cjs.map +1 -0
- package/dist/debouncer/useDebouncer.d.cts +133 -0
- package/dist/debouncer/useDebouncer.d.ts +133 -0
- package/dist/debouncer/useDebouncer.js +128 -0
- package/dist/debouncer/useDebouncer.js.map +1 -0
- package/dist/index.cjs +66 -0
- package/dist/index.d.cts +30 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +32 -0
- package/dist/provider/PacerProvider.cjs +26 -0
- package/dist/provider/PacerProvider.cjs.map +1 -0
- package/dist/provider/PacerProvider.d.cts +33 -0
- package/dist/provider/PacerProvider.d.ts +33 -0
- package/dist/provider/PacerProvider.js +24 -0
- package/dist/provider/PacerProvider.js.map +1 -0
- package/dist/provider/index.cjs +5 -0
- package/dist/provider/index.d.cts +2 -0
- package/dist/provider/index.d.ts +2 -0
- package/dist/provider/index.js +3 -0
- package/dist/queuer/index.cjs +14 -0
- package/dist/queuer/index.d.cts +5 -0
- package/dist/queuer/index.d.ts +5 -0
- package/dist/queuer/index.js +7 -0
- package/dist/queuer/useQueuedState.cjs +129 -0
- package/dist/queuer/useQueuedState.cjs.map +1 -0
- package/dist/queuer/useQueuedState.d.cts +123 -0
- package/dist/queuer/useQueuedState.d.ts +123 -0
- package/dist/queuer/useQueuedState.js +129 -0
- package/dist/queuer/useQueuedState.js.map +1 -0
- package/dist/queuer/useQueuedValue.cjs +115 -0
- package/dist/queuer/useQueuedValue.cjs.map +1 -0
- package/dist/queuer/useQueuedValue.d.cts +106 -0
- package/dist/queuer/useQueuedValue.d.ts +106 -0
- package/dist/queuer/useQueuedValue.js +115 -0
- package/dist/queuer/useQueuedValue.js.map +1 -0
- package/dist/queuer/useQueuer.cjs +157 -0
- package/dist/queuer/useQueuer.cjs.map +1 -0
- package/dist/queuer/useQueuer.d.cts +166 -0
- package/dist/queuer/useQueuer.d.ts +166 -0
- package/dist/queuer/useQueuer.js +157 -0
- package/dist/queuer/useQueuer.js.map +1 -0
- package/dist/rate-limiter/index.cjs +16 -0
- package/dist/rate-limiter/index.d.cts +6 -0
- package/dist/rate-limiter/index.d.ts +6 -0
- package/dist/rate-limiter/index.js +8 -0
- package/dist/rate-limiter/useRateLimitedCallback.cjs +65 -0
- package/dist/rate-limiter/useRateLimitedCallback.cjs.map +1 -0
- package/dist/rate-limiter/useRateLimitedCallback.d.cts +62 -0
- package/dist/rate-limiter/useRateLimitedCallback.d.ts +62 -0
- package/dist/rate-limiter/useRateLimitedCallback.js +65 -0
- package/dist/rate-limiter/useRateLimitedCallback.js.map +1 -0
- package/dist/rate-limiter/useRateLimitedState.cjs +115 -0
- package/dist/rate-limiter/useRateLimitedState.cjs.map +1 -0
- package/dist/rate-limiter/useRateLimitedState.d.cts +108 -0
- package/dist/rate-limiter/useRateLimitedState.d.ts +108 -0
- package/dist/rate-limiter/useRateLimitedState.js +115 -0
- package/dist/rate-limiter/useRateLimitedState.js.map +1 -0
- package/dist/rate-limiter/useRateLimitedValue.cjs +102 -0
- package/dist/rate-limiter/useRateLimitedValue.cjs.map +1 -0
- package/dist/rate-limiter/useRateLimitedValue.d.cts +97 -0
- package/dist/rate-limiter/useRateLimitedValue.d.ts +97 -0
- package/dist/rate-limiter/useRateLimitedValue.js +102 -0
- package/dist/rate-limiter/useRateLimitedValue.js.map +1 -0
- package/dist/rate-limiter/useRateLimiter.cjs +162 -0
- package/dist/rate-limiter/useRateLimiter.cjs.map +1 -0
- package/dist/rate-limiter/useRateLimiter.d.cts +172 -0
- package/dist/rate-limiter/useRateLimiter.d.ts +172 -0
- package/dist/rate-limiter/useRateLimiter.js +162 -0
- package/dist/rate-limiter/useRateLimiter.js.map +1 -0
- package/dist/throttler/index.cjs +16 -0
- package/dist/throttler/index.d.cts +6 -0
- package/dist/throttler/index.d.ts +6 -0
- package/dist/throttler/index.js +8 -0
- package/dist/throttler/useThrottledCallback.cjs +49 -0
- package/dist/throttler/useThrottledCallback.cjs.map +1 -0
- package/dist/throttler/useThrottledCallback.d.cts +46 -0
- package/dist/throttler/useThrottledCallback.d.ts +46 -0
- package/dist/throttler/useThrottledCallback.js +49 -0
- package/dist/throttler/useThrottledCallback.js.map +1 -0
- package/dist/throttler/useThrottledState.cjs +100 -0
- package/dist/throttler/useThrottledState.cjs.map +1 -0
- package/dist/throttler/useThrottledState.d.cts +93 -0
- package/dist/throttler/useThrottledState.d.ts +93 -0
- package/dist/throttler/useThrottledState.js +100 -0
- package/dist/throttler/useThrottledState.js.map +1 -0
- package/dist/throttler/useThrottledValue.cjs +91 -0
- package/dist/throttler/useThrottledValue.cjs.map +1 -0
- package/dist/throttler/useThrottledValue.d.cts +86 -0
- package/dist/throttler/useThrottledValue.d.ts +86 -0
- package/dist/throttler/useThrottledValue.js +91 -0
- package/dist/throttler/useThrottledValue.js.map +1 -0
- package/dist/throttler/useThrottler.cjs +133 -0
- package/dist/throttler/useThrottler.cjs.map +1 -0
- package/dist/throttler/useThrottler.d.cts +138 -0
- package/dist/throttler/useThrottler.d.ts +138 -0
- package/dist/throttler/useThrottler.js +133 -0
- package/dist/throttler/useThrottler.js.map +1 -0
- package/dist/types/index.cjs +9 -0
- package/dist/types/index.d.cts +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.js +3 -0
- package/dist/utils/index.cjs +9 -0
- package/dist/utils/index.d.cts +1 -0
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/index.js +3 -0
- package/package.json +118 -7
- package/src/async-batcher/index.ts +4 -0
- package/src/async-batcher/useAsyncBatchedCallback.ts +54 -0
- package/src/async-batcher/useAsyncBatcher.ts +249 -0
- package/src/async-debouncer/index.ts +5 -0
- package/src/async-debouncer/useAsyncDebouncedCallback.ts +54 -0
- package/src/async-debouncer/useAsyncDebouncer.ts +235 -0
- package/src/async-queuer/index.ts +4 -0
- package/src/async-queuer/useAsyncQueuedState.ts +165 -0
- package/src/async-queuer/useAsyncQueuer.ts +249 -0
- package/src/async-rate-limiter/index.ts +5 -0
- package/src/async-rate-limiter/useAsyncRateLimitedCallback.ts +69 -0
- package/src/async-rate-limiter/useAsyncRateLimiter.ts +261 -0
- package/src/async-retryer/index.ts +2 -0
- package/src/async-throttler/index.ts +5 -0
- package/src/async-throttler/useAsyncThrottledCallback.ts +52 -0
- package/src/async-throttler/useAsyncThrottler.ts +244 -0
- package/src/batcher/index.ts +4 -0
- package/src/batcher/useBatchedCallback.ts +50 -0
- package/src/batcher/useBatcher.ts +203 -0
- package/src/debouncer/index.ts +7 -0
- package/src/debouncer/useDebouncedCallback.ts +51 -0
- package/src/debouncer/useDebouncedState.ts +109 -0
- package/src/debouncer/useDebouncedValue.ts +112 -0
- package/src/debouncer/useDebouncer.ts +189 -0
- package/src/index.ts +56 -0
- package/src/provider/PacerProvider.tsx +70 -0
- package/src/provider/index.ts +1 -0
- package/src/queuer/index.ts +5 -0
- package/src/queuer/useQueuedState.ts +133 -0
- package/src/queuer/useQueuedValue.ts +129 -0
- package/src/queuer/useQueuer.ts +213 -0
- package/src/rate-limiter/index.ts +6 -0
- package/src/rate-limiter/useRateLimitedCallback.ts +68 -0
- package/src/rate-limiter/useRateLimitedState.ts +124 -0
- package/src/rate-limiter/useRateLimitedValue.ts +110 -0
- package/src/rate-limiter/useRateLimiter.ts +222 -0
- package/src/throttler/index.ts +7 -0
- package/src/throttler/useThrottledCallback.ts +52 -0
- package/src/throttler/useThrottledState.ts +121 -0
- package/src/throttler/useThrottledValue.ts +107 -0
- package/src/throttler/useThrottler.ts +194 -0
- package/src/types/index.ts +1 -0
- package/src/utils/index.ts +1 -0
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import { useEffect, useMemo, useState } from 'preact/hooks'
|
|
2
|
+
import { AsyncThrottler } from '@tanstack/pacer/async-throttler'
|
|
3
|
+
import { useStore } from '@tanstack/preact-store'
|
|
4
|
+
import { useDefaultPacerOptions } from '../provider/PacerProvider'
|
|
5
|
+
import type { Store } from '@tanstack/preact-store'
|
|
6
|
+
import type { AnyAsyncFunction } from '@tanstack/pacer/types'
|
|
7
|
+
import type {
|
|
8
|
+
AsyncThrottlerOptions,
|
|
9
|
+
AsyncThrottlerState,
|
|
10
|
+
} from '@tanstack/pacer/async-throttler'
|
|
11
|
+
import type { ComponentChildren } from 'preact'
|
|
12
|
+
|
|
13
|
+
export interface PreactAsyncThrottler<
|
|
14
|
+
TFn extends AnyAsyncFunction,
|
|
15
|
+
TSelected = {},
|
|
16
|
+
> extends Omit<AsyncThrottler<TFn>, 'store'> {
|
|
17
|
+
/**
|
|
18
|
+
* A Preact HOC (Higher Order Component) that allows you to subscribe to the async throttler state.
|
|
19
|
+
*
|
|
20
|
+
* This is useful for opting into state re-renders for specific parts of the throttler state
|
|
21
|
+
* deep in your component tree without needing to pass a selector to the hook.
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>
|
|
25
|
+
* {({ isPending }) => (
|
|
26
|
+
* <div>{isPending ? 'Loading...' : 'Ready'}</div>
|
|
27
|
+
* )}
|
|
28
|
+
* </throttler.Subscribe>
|
|
29
|
+
*/
|
|
30
|
+
Subscribe: <TSelected>(props: {
|
|
31
|
+
selector: (state: AsyncThrottlerState<TFn>) => TSelected
|
|
32
|
+
children: ((state: TSelected) => ComponentChildren) | ComponentChildren
|
|
33
|
+
}) => ComponentChildren
|
|
34
|
+
/**
|
|
35
|
+
* Reactive state that will be updated and re-rendered when the throttler state changes
|
|
36
|
+
*
|
|
37
|
+
* Use this instead of `throttler.store.state`
|
|
38
|
+
*/
|
|
39
|
+
readonly state: Readonly<TSelected>
|
|
40
|
+
/**
|
|
41
|
+
* @deprecated Use `throttler.state` instead of `throttler.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<AsyncThrottlerState<TFn>>>
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* A low-level Preact hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.
|
|
50
|
+
*
|
|
51
|
+
* This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that
|
|
52
|
+
* you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).
|
|
53
|
+
*
|
|
54
|
+
* Async throttling ensures an async function executes at most once within a specified time window,
|
|
55
|
+
* regardless of how many times it is called. This is useful for rate-limiting expensive API calls,
|
|
56
|
+
* database operations, or other async tasks.
|
|
57
|
+
*
|
|
58
|
+
* Unlike the non-async Throttler, this async version supports returning values from the throttled function,
|
|
59
|
+
* making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
|
|
60
|
+
* instead of setting the result on a state variable from within the throttled function.
|
|
61
|
+
*
|
|
62
|
+
* Error Handling:
|
|
63
|
+
* - If an `onError` handler is provided, it will be called with the error and throttler instance
|
|
64
|
+
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
65
|
+
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
66
|
+
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
67
|
+
* - The error state can be checked using the underlying AsyncThrottler instance
|
|
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 `throttler.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
|
+
* - `errorCount`: Number of function executions that have resulted in errors
|
|
92
|
+
* - `isExecuting`: Whether the throttled function is currently executing asynchronously
|
|
93
|
+
* - `isPending`: Whether the throttler is waiting for the timeout to trigger execution
|
|
94
|
+
* - `lastArgs`: The arguments from the most recent call to maybeExecute
|
|
95
|
+
* - `lastExecutionTime`: Timestamp of the last function execution in milliseconds
|
|
96
|
+
* - `lastResult`: The result from the most recent successful function execution
|
|
97
|
+
* - `nextExecutionTime`: Timestamp when the next execution can occur in milliseconds
|
|
98
|
+
* - `settleCount`: Number of function executions that have completed (success or error)
|
|
99
|
+
* - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing' | 'settled')
|
|
100
|
+
* - `successCount`: Number of function executions that have completed successfully
|
|
101
|
+
*
|
|
102
|
+
* @example
|
|
103
|
+
* ```tsx
|
|
104
|
+
* // Default behavior - no reactive state subscriptions
|
|
105
|
+
* const asyncThrottler = useAsyncThrottler(
|
|
106
|
+
* async (id: string) => {
|
|
107
|
+
* const data = await api.fetchData(id);
|
|
108
|
+
* return data; // Return value is preserved
|
|
109
|
+
* },
|
|
110
|
+
* { wait: 1000 }
|
|
111
|
+
* );
|
|
112
|
+
*
|
|
113
|
+
* // Subscribe to state changes deep in component tree using Subscribe HOC
|
|
114
|
+
* <asyncThrottler.Subscribe selector={(state) => ({ isPending: state.isPending })}>
|
|
115
|
+
* {({ isPending }) => (
|
|
116
|
+
* <div>{isPending ? 'Processing...' : 'Ready'}</div>
|
|
117
|
+
* )}
|
|
118
|
+
* </asyncThrottler.Subscribe>
|
|
119
|
+
*
|
|
120
|
+
* // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)
|
|
121
|
+
* const asyncThrottler = useAsyncThrottler(
|
|
122
|
+
* async (id: string) => {
|
|
123
|
+
* const data = await api.fetchData(id);
|
|
124
|
+
* return data;
|
|
125
|
+
* },
|
|
126
|
+
* { wait: 1000 },
|
|
127
|
+
* (state) => ({
|
|
128
|
+
* isExecuting: state.isExecuting,
|
|
129
|
+
* isPending: state.isPending,
|
|
130
|
+
* status: state.status
|
|
131
|
+
* })
|
|
132
|
+
* );
|
|
133
|
+
*
|
|
134
|
+
* // Opt-in to re-render when results are available (optimized for data display)
|
|
135
|
+
* const asyncThrottler = useAsyncThrottler(
|
|
136
|
+
* async (id: string) => {
|
|
137
|
+
* const data = await api.fetchData(id);
|
|
138
|
+
* return data;
|
|
139
|
+
* },
|
|
140
|
+
* { wait: 1000 },
|
|
141
|
+
* (state) => ({
|
|
142
|
+
* lastResult: state.lastResult,
|
|
143
|
+
* successCount: state.successCount,
|
|
144
|
+
* settleCount: state.settleCount
|
|
145
|
+
* })
|
|
146
|
+
* );
|
|
147
|
+
*
|
|
148
|
+
* // Opt-in to re-render when error state changes (optimized for error handling)
|
|
149
|
+
* const asyncThrottler = useAsyncThrottler(
|
|
150
|
+
* async (id: string) => {
|
|
151
|
+
* const data = await api.fetchData(id);
|
|
152
|
+
* return data;
|
|
153
|
+
* },
|
|
154
|
+
* {
|
|
155
|
+
* wait: 1000,
|
|
156
|
+
* onError: (error) => console.error('API call failed:', error)
|
|
157
|
+
* },
|
|
158
|
+
* (state) => ({
|
|
159
|
+
* errorCount: state.errorCount,
|
|
160
|
+
* status: state.status
|
|
161
|
+
* })
|
|
162
|
+
* );
|
|
163
|
+
*
|
|
164
|
+
* // Opt-in to re-render when timing information changes (optimized for timing displays)
|
|
165
|
+
* const asyncThrottler = useAsyncThrottler(
|
|
166
|
+
* async (id: string) => {
|
|
167
|
+
* const data = await api.fetchData(id);
|
|
168
|
+
* return data;
|
|
169
|
+
* },
|
|
170
|
+
* { wait: 1000 },
|
|
171
|
+
* (state) => ({
|
|
172
|
+
* lastExecutionTime: state.lastExecutionTime,
|
|
173
|
+
* nextExecutionTime: state.nextExecutionTime
|
|
174
|
+
* })
|
|
175
|
+
* );
|
|
176
|
+
*
|
|
177
|
+
* // With state management and return value
|
|
178
|
+
* const [data, setData] = useState(null);
|
|
179
|
+
* const { maybeExecute, state } = useAsyncThrottler(
|
|
180
|
+
* async (query) => {
|
|
181
|
+
* const result = await searchAPI(query);
|
|
182
|
+
* setData(result);
|
|
183
|
+
* return result; // Return value can be used by the caller
|
|
184
|
+
* },
|
|
185
|
+
* {
|
|
186
|
+
* wait: 2000,
|
|
187
|
+
* leading: true, // Execute immediately on first call
|
|
188
|
+
* trailing: false // Skip trailing edge updates
|
|
189
|
+
* }
|
|
190
|
+
* );
|
|
191
|
+
*
|
|
192
|
+
* // Access the selected state (will be empty object {} unless selector provided)
|
|
193
|
+
* const { isExecuting, lastResult } = state;
|
|
194
|
+
* ```
|
|
195
|
+
*/
|
|
196
|
+
export function useAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}>(
|
|
197
|
+
fn: TFn,
|
|
198
|
+
options: AsyncThrottlerOptions<TFn>,
|
|
199
|
+
selector: (state: AsyncThrottlerState<TFn>) => TSelected = () =>
|
|
200
|
+
({}) as TSelected,
|
|
201
|
+
): PreactAsyncThrottler<TFn, TSelected> {
|
|
202
|
+
const mergedOptions = {
|
|
203
|
+
...useDefaultPacerOptions().asyncThrottler,
|
|
204
|
+
...options,
|
|
205
|
+
} as AsyncThrottlerOptions<TFn>
|
|
206
|
+
|
|
207
|
+
const [asyncThrottler] = useState(() => {
|
|
208
|
+
const throttlerInstance = new AsyncThrottler<TFn>(
|
|
209
|
+
fn,
|
|
210
|
+
mergedOptions,
|
|
211
|
+
) as unknown as PreactAsyncThrottler<TFn, TSelected>
|
|
212
|
+
|
|
213
|
+
throttlerInstance.Subscribe = function Subscribe<TSelected>(props: {
|
|
214
|
+
selector: (state: AsyncThrottlerState<TFn>) => TSelected
|
|
215
|
+
children: ((state: TSelected) => ComponentChildren) | ComponentChildren
|
|
216
|
+
}) {
|
|
217
|
+
const selected = useStore(throttlerInstance.store, props.selector)
|
|
218
|
+
|
|
219
|
+
return typeof props.children === 'function'
|
|
220
|
+
? props.children(selected)
|
|
221
|
+
: props.children
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
return throttlerInstance
|
|
225
|
+
})
|
|
226
|
+
|
|
227
|
+
asyncThrottler.fn = fn
|
|
228
|
+
asyncThrottler.setOptions(mergedOptions)
|
|
229
|
+
|
|
230
|
+
const state = useStore(asyncThrottler.store, selector)
|
|
231
|
+
|
|
232
|
+
useEffect(() => {
|
|
233
|
+
return () => asyncThrottler.cancel()
|
|
234
|
+
}, [asyncThrottler])
|
|
235
|
+
|
|
236
|
+
return useMemo(
|
|
237
|
+
() =>
|
|
238
|
+
({
|
|
239
|
+
...asyncThrottler,
|
|
240
|
+
state,
|
|
241
|
+
}) as PreactAsyncThrottler<TFn, TSelected>, // omit `store` in favor of `state`
|
|
242
|
+
[asyncThrottler, state],
|
|
243
|
+
)
|
|
244
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { useCallback } from 'preact/hooks'
|
|
2
|
+
import { useBatcher } from './useBatcher'
|
|
3
|
+
import type { BatcherOptions } from '@tanstack/pacer/batcher'
|
|
4
|
+
import type { AnyFunction } from '@tanstack/pacer/types'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* A Preact hook that creates a batched version of a callback function.
|
|
8
|
+
* This hook is essentially a wrapper around the basic `batch` function
|
|
9
|
+
* that is exported from `@tanstack/pacer`,
|
|
10
|
+
* but optimized for Preact with reactive options and a stable function reference.
|
|
11
|
+
*
|
|
12
|
+
* The batched function will collect individual calls into batches and execute them
|
|
13
|
+
* when batch conditions are met (max size reached, wait time elapsed, or custom logic).
|
|
14
|
+
*
|
|
15
|
+
* This hook provides a simpler API compared to `useBatcher`, making it ideal for basic
|
|
16
|
+
* batching needs. However, it does not expose the underlying Batcher instance.
|
|
17
|
+
*
|
|
18
|
+
* For advanced usage requiring features like:
|
|
19
|
+
* - Manual batch execution
|
|
20
|
+
* - Access to batch state and metrics
|
|
21
|
+
* - Custom useCallback dependencies
|
|
22
|
+
*
|
|
23
|
+
* Consider using the `useBatcher` hook instead.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```tsx
|
|
27
|
+
* // Batch analytics events
|
|
28
|
+
* const trackEvents = useBatchedCallback((events: AnalyticsEvent[]) => {
|
|
29
|
+
* sendAnalytics(events);
|
|
30
|
+
* }, {
|
|
31
|
+
* maxSize: 5, // Process when 5 events collected
|
|
32
|
+
* wait: 2000 // Or after 2 seconds
|
|
33
|
+
* });
|
|
34
|
+
*
|
|
35
|
+
* // Use in event handlers
|
|
36
|
+
* <button onClick={() => trackEvents({ type: 'click', target: 'button' })}>
|
|
37
|
+
* Click me
|
|
38
|
+
* </button>
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
export function useBatchedCallback<TFn extends AnyFunction>(
|
|
42
|
+
fn: (items: Array<Parameters<TFn>[0]>) => void,
|
|
43
|
+
options: BatcherOptions<Parameters<TFn>[0]>,
|
|
44
|
+
): (...args: Parameters<TFn>) => void {
|
|
45
|
+
const batchedFn = useBatcher(fn, options).addItem
|
|
46
|
+
return useCallback(
|
|
47
|
+
(...args: Parameters<TFn>) => batchedFn(args[0]),
|
|
48
|
+
[batchedFn],
|
|
49
|
+
)
|
|
50
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { useMemo, useState } from 'preact/hooks'
|
|
2
|
+
import { Batcher } from '@tanstack/pacer/batcher'
|
|
3
|
+
import { useStore } from '@tanstack/preact-store'
|
|
4
|
+
import { useDefaultPacerOptions } from '../provider/PacerProvider'
|
|
5
|
+
import type { Store } from '@tanstack/preact-store'
|
|
6
|
+
import type { BatcherOptions, BatcherState } from '@tanstack/pacer/batcher'
|
|
7
|
+
import type { ComponentChildren } from 'preact'
|
|
8
|
+
|
|
9
|
+
export interface PreactBatcher<TValue, TSelected = {}> extends Omit<
|
|
10
|
+
Batcher<TValue>,
|
|
11
|
+
'store'
|
|
12
|
+
> {
|
|
13
|
+
/**
|
|
14
|
+
* A Preact HOC (Higher Order Component) that allows you to subscribe to the batcher state.
|
|
15
|
+
*
|
|
16
|
+
* This is useful for opting into state re-renders for specific parts of the batcher state
|
|
17
|
+
* deep in your component tree without needing to pass a selector to the hook.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* <batcher.Subscribe selector={(state) => ({ size: state.size })}>
|
|
21
|
+
* {({ size }) => (
|
|
22
|
+
* <div>Batch Size: {size}</div>
|
|
23
|
+
* )}
|
|
24
|
+
* </batcher.Subscribe>
|
|
25
|
+
*/
|
|
26
|
+
Subscribe: <TSelected>(props: {
|
|
27
|
+
selector: (state: BatcherState<TValue>) => TSelected
|
|
28
|
+
children: ((state: TSelected) => ComponentChildren) | ComponentChildren
|
|
29
|
+
}) => ComponentChildren
|
|
30
|
+
/**
|
|
31
|
+
* Reactive state that will be updated and re-rendered when the batcher state changes
|
|
32
|
+
*
|
|
33
|
+
* Use this instead of `batcher.store.state`
|
|
34
|
+
*/
|
|
35
|
+
readonly state: Readonly<TSelected>
|
|
36
|
+
/**
|
|
37
|
+
* @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state.
|
|
38
|
+
* The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.
|
|
39
|
+
* Although, you can make the state reactive by using the `useStore` in your own usage.
|
|
40
|
+
*/
|
|
41
|
+
readonly store: Store<Readonly<BatcherState<TValue>>>
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* A Preact hook that creates and manages a Batcher instance.
|
|
46
|
+
*
|
|
47
|
+
* This is a lower-level hook that provides direct access to the Batcher's functionality without
|
|
48
|
+
* any built-in state management. This allows you to integrate it with any state management solution
|
|
49
|
+
* you prefer (useState, Redux, Zustand, etc.) by utilizing the onItemsChange callback.
|
|
50
|
+
*
|
|
51
|
+
* The Batcher collects items and processes them in batches based on configurable conditions:
|
|
52
|
+
* - Maximum batch size
|
|
53
|
+
* - Time-based batching (process after X milliseconds)
|
|
54
|
+
* - Custom batch processing logic via getShouldExecute
|
|
55
|
+
*
|
|
56
|
+
* ## State Management and Selector
|
|
57
|
+
*
|
|
58
|
+
* The hook uses TanStack Store for reactive state management. You can subscribe to state changes
|
|
59
|
+
* in two ways:
|
|
60
|
+
*
|
|
61
|
+
* **1. Using `batcher.Subscribe` HOC (Recommended for component tree subscriptions)**
|
|
62
|
+
*
|
|
63
|
+
* Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
|
|
64
|
+
* needing to pass a selector to the hook. This is ideal when you want to subscribe to state
|
|
65
|
+
* in child components.
|
|
66
|
+
*
|
|
67
|
+
* **2. Using the `selector` parameter (For hook-level subscriptions)**
|
|
68
|
+
*
|
|
69
|
+
* The `selector` parameter allows you to specify which state changes will trigger a re-render
|
|
70
|
+
* at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
|
|
71
|
+
* state changes occur.
|
|
72
|
+
*
|
|
73
|
+
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
74
|
+
* tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
|
|
75
|
+
* re-renders and gives you full control over when your component updates.
|
|
76
|
+
*
|
|
77
|
+
* Available state properties:
|
|
78
|
+
* - `executionCount`: Number of batch executions that have been completed
|
|
79
|
+
* - `isEmpty`: Whether the batcher has no items to process
|
|
80
|
+
* - `isPending`: Whether the batcher is waiting for the timeout to trigger batch processing
|
|
81
|
+
* - `isRunning`: Whether the batcher is active and will process items automatically
|
|
82
|
+
* - `items`: Array of items currently queued for batch processing
|
|
83
|
+
* - `size`: Number of items currently in the batch queue
|
|
84
|
+
* - `status`: Current processing status ('idle' | 'pending')
|
|
85
|
+
* - `totalItemsProcessed`: Total number of items processed across all batches
|
|
86
|
+
*
|
|
87
|
+
* @example
|
|
88
|
+
* ```tsx
|
|
89
|
+
* // Default behavior - no reactive state subscriptions
|
|
90
|
+
* const batcher = useBatcher<number>(
|
|
91
|
+
* (items) => console.log('Processing batch:', items),
|
|
92
|
+
* { maxSize: 5, wait: 2000 }
|
|
93
|
+
* );
|
|
94
|
+
*
|
|
95
|
+
* // Subscribe to state changes deep in component tree using Subscribe HOC
|
|
96
|
+
* <batcher.Subscribe selector={(state) => ({ size: state.size })}>
|
|
97
|
+
* {({ size }) => (
|
|
98
|
+
* <div>Batch Size: {size}</div>
|
|
99
|
+
* )}
|
|
100
|
+
* </batcher.Subscribe>
|
|
101
|
+
*
|
|
102
|
+
* // Opt-in to re-render when batch size changes at hook level (optimized for displaying queue size)
|
|
103
|
+
* const batcher = useBatcher<number>(
|
|
104
|
+
* (items) => console.log('Processing batch:', items),
|
|
105
|
+
* { maxSize: 5, wait: 2000 },
|
|
106
|
+
* (state) => ({
|
|
107
|
+
* size: state.size,
|
|
108
|
+
* isEmpty: state.isEmpty
|
|
109
|
+
* })
|
|
110
|
+
* );
|
|
111
|
+
*
|
|
112
|
+
* // Opt-in to re-render when execution metrics change (optimized for stats display)
|
|
113
|
+
* const batcher = useBatcher<number>(
|
|
114
|
+
* (items) => console.log('Processing batch:', items),
|
|
115
|
+
* { maxSize: 5, wait: 2000 },
|
|
116
|
+
* (state) => ({
|
|
117
|
+
* executionCount: state.executionCount,
|
|
118
|
+
* totalItemsProcessed: state.totalItemsProcessed
|
|
119
|
+
* })
|
|
120
|
+
* );
|
|
121
|
+
*
|
|
122
|
+
* // Opt-in to re-render when processing state changes (optimized for loading indicators)
|
|
123
|
+
* const batcher = useBatcher<number>(
|
|
124
|
+
* (items) => console.log('Processing batch:', items),
|
|
125
|
+
* { maxSize: 5, wait: 2000 },
|
|
126
|
+
* (state) => ({
|
|
127
|
+
* isPending: state.isPending,
|
|
128
|
+
* isRunning: state.isRunning,
|
|
129
|
+
* status: state.status
|
|
130
|
+
* })
|
|
131
|
+
* );
|
|
132
|
+
*
|
|
133
|
+
* // Example with custom state management and batching
|
|
134
|
+
* const [items, setItems] = useState([]);
|
|
135
|
+
*
|
|
136
|
+
* const batcher = useBatcher<number>(
|
|
137
|
+
* (items) => console.log('Processing batch:', items),
|
|
138
|
+
* {
|
|
139
|
+
* maxSize: 5,
|
|
140
|
+
* wait: 2000,
|
|
141
|
+
* onItemsChange: (batcher) => setItems(batcher.peekAllItems()),
|
|
142
|
+
* getShouldExecute: (items) => items.length >= 3
|
|
143
|
+
* }
|
|
144
|
+
* );
|
|
145
|
+
*
|
|
146
|
+
* // Add items to batch - they'll be processed when conditions are met
|
|
147
|
+
* batcher.addItem(1);
|
|
148
|
+
* batcher.addItem(2);
|
|
149
|
+
* batcher.addItem(3); // Triggers batch processing
|
|
150
|
+
*
|
|
151
|
+
* // Control the batcher
|
|
152
|
+
* batcher.stop(); // Pause batching
|
|
153
|
+
* batcher.start(); // Resume batching
|
|
154
|
+
*
|
|
155
|
+
* // Access the selected state (will be empty object {} unless selector provided)
|
|
156
|
+
* const { size, isPending } = batcher.state;
|
|
157
|
+
* ```
|
|
158
|
+
*/
|
|
159
|
+
export function useBatcher<TValue, TSelected = {}>(
|
|
160
|
+
fn: (items: Array<TValue>) => void,
|
|
161
|
+
options: BatcherOptions<TValue> = {},
|
|
162
|
+
selector: (state: BatcherState<TValue>) => TSelected = () =>
|
|
163
|
+
({}) as TSelected,
|
|
164
|
+
): PreactBatcher<TValue, TSelected> {
|
|
165
|
+
const mergedOptions = {
|
|
166
|
+
...useDefaultPacerOptions().batcher,
|
|
167
|
+
...options,
|
|
168
|
+
} as BatcherOptions<TValue>
|
|
169
|
+
|
|
170
|
+
const [batcher] = useState(() => {
|
|
171
|
+
const batcherInstance = new Batcher<TValue>(
|
|
172
|
+
fn,
|
|
173
|
+
mergedOptions,
|
|
174
|
+
) as unknown as PreactBatcher<TValue, TSelected>
|
|
175
|
+
|
|
176
|
+
batcherInstance.Subscribe = function Subscribe<TSelected>(props: {
|
|
177
|
+
selector: (state: BatcherState<TValue>) => TSelected
|
|
178
|
+
children: ((state: TSelected) => ComponentChildren) | ComponentChildren
|
|
179
|
+
}) {
|
|
180
|
+
const selected = useStore(batcherInstance.store, props.selector)
|
|
181
|
+
|
|
182
|
+
return typeof props.children === 'function'
|
|
183
|
+
? props.children(selected)
|
|
184
|
+
: props.children
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
return batcherInstance
|
|
188
|
+
})
|
|
189
|
+
|
|
190
|
+
batcher.fn = fn
|
|
191
|
+
batcher.setOptions(mergedOptions)
|
|
192
|
+
|
|
193
|
+
const state = useStore(batcher.store, selector)
|
|
194
|
+
|
|
195
|
+
return useMemo(
|
|
196
|
+
() =>
|
|
197
|
+
({
|
|
198
|
+
...batcher,
|
|
199
|
+
state,
|
|
200
|
+
}) as PreactBatcher<TValue, TSelected>, // omit `store` in favor of `state`
|
|
201
|
+
[batcher, state],
|
|
202
|
+
)
|
|
203
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// re-export everything from the core pacer package, BUT ONLY from the debouncer module
|
|
2
|
+
export * from '@tanstack/pacer/debouncer'
|
|
3
|
+
|
|
4
|
+
export * from './useDebouncedCallback'
|
|
5
|
+
export * from './useDebouncedState'
|
|
6
|
+
export * from './useDebouncedValue'
|
|
7
|
+
export * from './useDebouncer'
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { useCallback } from 'preact/hooks'
|
|
2
|
+
import { useDebouncer } from './useDebouncer'
|
|
3
|
+
import type { DebouncerOptions } from '@tanstack/pacer/debouncer'
|
|
4
|
+
import type { AnyFunction } from '@tanstack/pacer/types'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* A Preact hook that creates a debounced version of a callback function.
|
|
8
|
+
* This hook is essentially a wrapper around the basic `debounce` function
|
|
9
|
+
* that is exported from `@tanstack/pacer`,
|
|
10
|
+
* but optimized for Preact with reactive options and a stable function reference.
|
|
11
|
+
*
|
|
12
|
+
* The debounced function will only execute after the specified wait time has elapsed
|
|
13
|
+
* since its last invocation. If called again before the wait time expires, the timer
|
|
14
|
+
* resets and starts waiting again.
|
|
15
|
+
*
|
|
16
|
+
* This hook provides a simpler API compared to `useDebouncer`, making it ideal for basic
|
|
17
|
+
* debouncing needs. However, it does not expose the underlying Debouncer instance.
|
|
18
|
+
*
|
|
19
|
+
* For advanced usage requiring features like:
|
|
20
|
+
* - Manual cancellation
|
|
21
|
+
* - Access to execution counts
|
|
22
|
+
* - Custom useCallback dependencies
|
|
23
|
+
*
|
|
24
|
+
* Consider using the `useDebouncer` hook instead.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```tsx
|
|
28
|
+
* // Debounce a search handler
|
|
29
|
+
* const handleSearch = useDebouncedCallback((query: string) => {
|
|
30
|
+
* fetchSearchResults(query);
|
|
31
|
+
* }, {
|
|
32
|
+
* wait: 500 // Wait 500ms between executions
|
|
33
|
+
* });
|
|
34
|
+
*
|
|
35
|
+
* // Use in an input
|
|
36
|
+
* <input
|
|
37
|
+
* type="search"
|
|
38
|
+
* onChange={(e) => handleSearch(e.target.value)}
|
|
39
|
+
* />
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
export function useDebouncedCallback<TFn extends AnyFunction>(
|
|
43
|
+
fn: TFn,
|
|
44
|
+
options: DebouncerOptions<TFn>,
|
|
45
|
+
): (...args: Parameters<TFn>) => void {
|
|
46
|
+
const debouncedFn = useDebouncer(fn, options).maybeExecute
|
|
47
|
+
return useCallback(
|
|
48
|
+
(...args: Parameters<TFn>) => debouncedFn(...args),
|
|
49
|
+
[debouncedFn],
|
|
50
|
+
)
|
|
51
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { useState } from 'preact/hooks'
|
|
2
|
+
import { useDebouncer } from './useDebouncer'
|
|
3
|
+
import type { Dispatch, StateUpdater } from 'preact/hooks'
|
|
4
|
+
import type { PreactDebouncer } from './useDebouncer'
|
|
5
|
+
import type {
|
|
6
|
+
DebouncerOptions,
|
|
7
|
+
DebouncerState,
|
|
8
|
+
} from '@tanstack/pacer/debouncer'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* A Preact hook that creates a debounced state value, combining Preact's useState with debouncing functionality.
|
|
12
|
+
* This hook provides both the current debounced value and methods to update it.
|
|
13
|
+
*
|
|
14
|
+
* The state value is only updated after the specified wait time has elapsed since the last update attempt.
|
|
15
|
+
* If another update is attempted before the wait time expires, the timer resets and starts waiting again.
|
|
16
|
+
* This is useful for handling frequent state updates that should be throttled, like search input values
|
|
17
|
+
* or window resize dimensions.
|
|
18
|
+
*
|
|
19
|
+
* The hook returns a tuple containing:
|
|
20
|
+
* - The current debounced value
|
|
21
|
+
* - A function to update the debounced value
|
|
22
|
+
* - The debouncer instance with additional control methods
|
|
23
|
+
*
|
|
24
|
+
* ## State Management and Selector
|
|
25
|
+
*
|
|
26
|
+
* The hook uses TanStack Store for reactive state management via the underlying debouncer instance.
|
|
27
|
+
* The `selector` parameter allows you to specify which debouncer 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 debouncer state properties:
|
|
36
|
+
* - `canLeadingExecute`: Whether the debouncer can execute on the leading edge
|
|
37
|
+
* - `executionCount`: Number of function executions that have been completed
|
|
38
|
+
* - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution
|
|
39
|
+
* - `lastArgs`: The arguments from the most recent call to maybeExecute
|
|
40
|
+
* - `status`: Current execution status ('disabled' | 'idle' | 'pending')
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```tsx
|
|
44
|
+
* // Default behavior - no reactive state subscriptions
|
|
45
|
+
* const [searchTerm, setSearchTerm, debouncer] = useDebouncedState('', {
|
|
46
|
+
* wait: 500 // Wait 500ms after last keystroke
|
|
47
|
+
* });
|
|
48
|
+
*
|
|
49
|
+
* // Opt-in to re-render when pending state changes (optimized for loading indicators)
|
|
50
|
+
* const [searchTerm, setSearchTerm, debouncer] = useDebouncedState(
|
|
51
|
+
* '',
|
|
52
|
+
* { wait: 500 },
|
|
53
|
+
* (state) => ({ isPending: state.isPending })
|
|
54
|
+
* );
|
|
55
|
+
*
|
|
56
|
+
* // Opt-in to re-render when execution count changes (optimized for tracking executions)
|
|
57
|
+
* const [searchTerm, setSearchTerm, debouncer] = useDebouncedState(
|
|
58
|
+
* '',
|
|
59
|
+
* { wait: 500 },
|
|
60
|
+
* (state) => ({ executionCount: state.executionCount })
|
|
61
|
+
* );
|
|
62
|
+
*
|
|
63
|
+
* // Opt-in to re-render when debouncing status changes (optimized for status display)
|
|
64
|
+
* const [searchTerm, setSearchTerm, debouncer] = useDebouncedState(
|
|
65
|
+
* '',
|
|
66
|
+
* { wait: 500 },
|
|
67
|
+
* (state) => ({
|
|
68
|
+
* status: state.status,
|
|
69
|
+
* canLeadingExecute: state.canLeadingExecute
|
|
70
|
+
* })
|
|
71
|
+
* );
|
|
72
|
+
*
|
|
73
|
+
* // Update value - will be debounced
|
|
74
|
+
* const handleChange = (e) => {
|
|
75
|
+
* setSearchTerm(e.target.value);
|
|
76
|
+
* };
|
|
77
|
+
*
|
|
78
|
+
* // Access the selected debouncer state (will be empty object {} unless selector provided)
|
|
79
|
+
* const { isPending, executionCount } = debouncer.state;
|
|
80
|
+
* ```
|
|
81
|
+
*/
|
|
82
|
+
export function useDebouncedState<
|
|
83
|
+
TValue,
|
|
84
|
+
TSelected = DebouncerState<Dispatch<StateUpdater<TValue>>>,
|
|
85
|
+
>(
|
|
86
|
+
value: TValue,
|
|
87
|
+
options: DebouncerOptions<Dispatch<StateUpdater<TValue>>>,
|
|
88
|
+
selector?: (
|
|
89
|
+
state: DebouncerState<Dispatch<StateUpdater<TValue>>>,
|
|
90
|
+
) => TSelected,
|
|
91
|
+
): [
|
|
92
|
+
TValue,
|
|
93
|
+
Dispatch<StateUpdater<TValue>>,
|
|
94
|
+
PreactDebouncer<Dispatch<StateUpdater<TValue>>, TSelected>,
|
|
95
|
+
] {
|
|
96
|
+
const [debouncedValue, setDebouncedValue] = useState(value)
|
|
97
|
+
const debouncer = useDebouncer(
|
|
98
|
+
setDebouncedValue,
|
|
99
|
+
options,
|
|
100
|
+
selector as (
|
|
101
|
+
state: DebouncerState<Dispatch<StateUpdater<TValue>>>,
|
|
102
|
+
) => TSelected,
|
|
103
|
+
)
|
|
104
|
+
return [
|
|
105
|
+
debouncedValue,
|
|
106
|
+
debouncer.maybeExecute as Dispatch<StateUpdater<TValue>>,
|
|
107
|
+
debouncer,
|
|
108
|
+
]
|
|
109
|
+
}
|