@himanshu-sorathiya/react-kit 1.0.26 → 1.0.28

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.
@@ -2,85 +2,938 @@
2
2
 
3
3
  import { Key } from 'react';
4
4
 
5
+ /**
6
+ * Adds an optional custom equality comparator to any hook that manages a
7
+ * value and needs to decide whether a "new" value is actually different
8
+ * enough to justify a re-render.
9
+ *
10
+ * Used by the `State` and `Value` variants of debounce/throttle/rate-limit
11
+ * (e.g. `useDebouncedValue`, `useThrottledState`) to avoid committing a
12
+ * value that is deeply/semantically equal to the value already held,
13
+ * which would otherwise trigger a wasted re-render.
14
+ *
15
+ * @example
16
+ * ```tsx
17
+ * useDebouncedValue(user, 300, {
18
+ * equalityFn: (previous, next) => previous.id === next.id,
19
+ * });
20
+ * ```
21
+ */
22
+ export interface EqualityFnOption<T> {
23
+ /**
24
+ * Called with the currently-held value and the candidate next value.
25
+ * Return `true` if they should be treated as equal (no update should be
26
+ * committed); return `false` to allow the update through.
27
+ *
28
+ * Defaults to `Object.is` when omitted, or when an invalid (non-function)
29
+ * value is provided — see the consuming hook's dev-mode warning.
30
+ */
31
+ equalityFn?: (previous: T, next: T) => boolean;
32
+ }
33
+ /**
34
+ * Configuration for `useDebouncer` and every hook built on top of it.
35
+ *
36
+ * @remarks
37
+ * `leading` and `trailing` may both be set to `false` at the same time —
38
+ * the hook will not silently correct this for you. That configuration
39
+ * means the debounced function will never run; a dev-mode warning is
40
+ * logged to help catch it early, but the choice itself is respected.
41
+ */
5
42
  export interface DebounceOptions {
43
+ /**
44
+ * A hard ceiling, in milliseconds, on how long invocation can be
45
+ * deferred. If a continuous stream of calls keeps pushing the trailing
46
+ * timer out, `maxWait` forces a synchronous invocation once this many
47
+ * milliseconds have elapsed since the current cycle began — regardless
48
+ * of whether the trailing window has settled yet.
49
+ *
50
+ * Only evaluated at the moment `run()` is called; it is not an
51
+ * independent background timer, so it can't fire while no calls are
52
+ * coming in.
53
+ *
54
+ * @defaultValue `undefined` (no ceiling)
55
+ */
6
56
  maxWait?: number;
57
+ /**
58
+ * When `true`, invokes on the leading edge — immediately, on the first
59
+ * call of a new debounce cycle (i.e. when no cycle is currently active).
60
+ *
61
+ * @defaultValue `false`
62
+ */
7
63
  leading?: boolean;
64
+ /**
65
+ * When `true`, invokes on the trailing edge — once `delay` milliseconds
66
+ * have elapsed with no further calls.
67
+ *
68
+ * Defaults to `true` regardless of `leading`'s value. With
69
+ * `{ leading: true, trailing: true }` (both edges enabled), a single
70
+ * isolated call only fires once (the leading edge) — the trailing edge
71
+ * only fires if at least one more call arrives before the window
72
+ * closes.
73
+ *
74
+ * @defaultValue `true`
75
+ */
8
76
  trailing?: boolean;
9
77
  }
10
- export interface UseDebounceReturn {
11
- run: <Args extends unknown[]>(func: (...args: Args) => void, ...args: Args) => void;
12
- cancel: () => void;
13
- flush: () => void;
14
- isPending: boolean;
15
- }
16
- export declare function useDebounce(delay: number, options?: DebounceOptions): UseDebounceReturn;
78
+ /**
79
+ * Options for `useDebouncedState`: all of {@link DebounceOptions}, plus an
80
+ * optional equality comparator used to skip committing a value equivalent
81
+ * to the one already held.
82
+ */
83
+ export type UseDebouncedStateOptions<T> = DebounceOptions & EqualityFnOption<T>;
84
+ /**
85
+ * Options for `useDebouncedValue`: all of {@link DebounceOptions}, plus an
86
+ * optional equality comparator used to skip committing a value equivalent
87
+ * to the one already held.
88
+ */
89
+ export type UseDebouncedValueOptions<T> = DebounceOptions & EqualityFnOption<T>;
90
+ /**
91
+ * The object returned by `useDebouncedCallback`.
92
+ */
17
93
  export interface UseDebouncedCallbackReturn<Args extends unknown[]> {
94
+ /**
95
+ * A stable, debounced wrapper around `func`. Safe to call from any
96
+ * event handler; internally always invokes the most recently rendered
97
+ * `func`, even though `debouncedFunc`'s own identity doesn't change
98
+ * across re-renders.
99
+ */
18
100
  debouncedFunc: (...args: Args) => void;
101
+ /** See {@link UseDebouncerReturn.cancel}. */
19
102
  cancel: () => void;
103
+ /** See {@link UseDebouncerReturn.flush}. */
20
104
  flush: () => void;
105
+ /** See {@link UseDebouncerReturn.isPending}. */
21
106
  isPending: boolean;
22
107
  }
108
+ /**
109
+ * Debounces a single function.
110
+ *
111
+ * `func` is captured in a ref and refreshed on every render — you can pass
112
+ * a fresh inline closure every time without resetting the pending debounce
113
+ * cycle, and the debounced wrapper always calls the *latest* `func`,
114
+ * closing over whatever props/state were current when it actually fires
115
+ * (never a stale closure from whenever the wrapper was first created).
116
+ *
117
+ * @example
118
+ * ```tsx
119
+ * function SearchBox() {
120
+ * const { debouncedFunc: handleSearch, isPending } = useDebouncedCallback(
121
+ * (query: string) => fetchResults(query),
122
+ * 400,
123
+ * );
124
+ *
125
+ * return (
126
+ * <>
127
+ * <input onChange={(e) => handleSearch(e.target.value)} />
128
+ * {isPending && <span>Typing…</span>}
129
+ * </>
130
+ * );
131
+ * }
132
+ * ```
133
+ *
134
+ * @param func - The function to debounce. Safe to pass a new closure on
135
+ * every render.
136
+ * @param delay - See {@link useDebouncer}.
137
+ * @param options - See {@link DebounceOptions}.
138
+ * @returns See {@link UseDebouncedCallbackReturn}.
139
+ */
23
140
  export declare function useDebouncedCallback<Args extends unknown[]>(func: (...args: Args) => void, delay: number, options?: DebounceOptions): UseDebouncedCallbackReturn<Args>;
141
+ /**
142
+ * The tuple returned by `useDebouncedState`, mirroring `useState`'s
143
+ * `[value, setValue]` shape with a third element carrying debounce
144
+ * controls.
145
+ */
24
146
  export type UseDebouncedStateReturn<T> = [
147
+ /** The current, committed state value. */
148
+ T,
149
+ /**
150
+ * Schedules a debounced update to state. Accepts either a plain value
151
+ * or a `useState`-style functional updater (`(previous) => next`).
152
+ *
153
+ * The functional-updater form composes correctly across multiple rapid
154
+ * calls made before the debounce settles — e.g. calling
155
+ * `setValue((p) => p + 1)` three times in a row schedules a cumulative
156
+ * `+3`, not three competing `+1`s racing to be "the" pending value.
157
+ * `previous` in that case refers to the most recently *scheduled*
158
+ * value, not necessarily the currently-committed state — this matters
159
+ * if you're chaining updates faster than the debounce settles.
160
+ */
161
+ (value: T | ((previous: T) => T)) => void,
162
+ {
163
+ /** See {@link UseDebouncerReturn.isPending}. */
164
+ isPending: boolean;
165
+ /**
166
+ * Cancels any pending debounced update. Also resyncs the internal
167
+ * "next value to commit" tracking back to the current committed
168
+ * state, so a subsequent functional update starts from the right
169
+ * baseline instead of building on a discarded value.
170
+ */
171
+ cancel: () => void;
172
+ /** See {@link UseDebouncerReturn.flush}. */
173
+ flush: () => void;
174
+ /**
175
+ * Bypasses debounce scheduling entirely and applies the value (or
176
+ * updater) immediately. Also cancels any debounced update that was
177
+ * still pending, so it can't land afterward and silently overwrite
178
+ * this forced value.
179
+ */
180
+ forceSetValue: (value: T | ((previous: T) => T)) => void;
181
+ }
182
+ ];
183
+ /**
184
+ * A `useState`-shaped hook whose setter defers its effect on state until
185
+ * the debounce window settles, instead of applying immediately.
186
+ *
187
+ * @example
188
+ * ```tsx
189
+ * function NoteEditor() {
190
+ * const [note, setNote, { isPending, flush, forceSetValue }] =
191
+ * useDebouncedState("", 800);
192
+ *
193
+ * return (
194
+ * <>
195
+ * <textarea onChange={(e) => setNote(e.target.value)} />
196
+ * <p>Committed: {note}</p>
197
+ * {isPending && <span>Unsaved changes…</span>}
198
+ * <button onClick={flush}>Save Now</button>
199
+ * <button onClick={() => forceSetValue("")}>Reset</button>
200
+ * </>
201
+ * );
202
+ * }
203
+ * ```
204
+ *
205
+ * @param initialValue - Initial state value, or a `useState`-style lazy
206
+ * initializer function (`() => T`).
207
+ * @param delay - See {@link useDebouncer}.
208
+ * @param options - See {@link UseDebouncedStateOptions}.
209
+ * @returns See {@link UseDebouncedStateReturn}.
210
+ */
211
+ export declare function useDebouncedState<T>(initialValue: T | (() => T), delay: number, options?: UseDebouncedStateOptions<T>): UseDebouncedStateReturn<T>;
212
+ /**
213
+ * The tuple returned by `useDebouncedValue`.
214
+ */
215
+ export type UseDebouncedValueReturn<T> = [
216
+ /** The debounced (lagging) mirror of the source value. */
25
217
  T,
26
- (value: T) => void,
27
218
  {
219
+ /** See {@link UseDebouncerReturn.isPending}. */
28
220
  isPending: boolean;
221
+ /** Cancels the pending sync to the latest source value. */
29
222
  cancel: () => void;
223
+ /** Immediately commits the latest source value, bypassing the delay. */
30
224
  flush: () => void;
31
- forceSetValue: (value: T) => void;
32
225
  }
33
226
  ];
34
- export declare function useDebouncedState<T>(initialValue: T | (() => T), delay: number, options?: DebounceOptions): UseDebouncedStateReturn<T>;
35
- export type UseDebouncedValueReturn<T> = T;
36
- export declare function useDebouncedValue<T>(value: T, delay: number, options?: DebounceOptions): UseDebouncedValueReturn<T>;
227
+ /**
228
+ * Mirrors `value`, but the mirror only updates `delay` milliseconds after
229
+ * `value` stops changing — a safe, stable dependency for an expensive
230
+ * effect (filtering, fetching) that shouldn't re-run on every keystroke.
231
+ *
232
+ * @example
233
+ * ```tsx
234
+ * function ProductFilterField() {
235
+ * const [query, setQuery] = useState("");
236
+ * const [debouncedQuery] = useDebouncedValue(query, 350);
237
+ *
238
+ * // `debouncedQuery` only updates 350ms after typing stops.
239
+ *
240
+ * return (
241
+ * <input value={query} onChange={(e) => setQuery(e.target.value)} />
242
+ * );
243
+ * }
244
+ * ```
245
+ *
246
+ * @param value - The source value to debounce. Every change re-arms the
247
+ * debounce window.
248
+ * @param delay - See {@link useDebouncer}.
249
+ * @param options - See {@link UseDebouncedValueOptions}.
250
+ * @returns See {@link UseDebouncedValueReturn}.
251
+ */
252
+ export declare function useDebouncedValue<T>(value: T, delay: number, options?: UseDebouncedValueOptions<T>): UseDebouncedValueReturn<T>;
253
+ /**
254
+ * The object returned by `useDebouncer`.
255
+ */
256
+ export interface UseDebouncerReturn {
257
+ /**
258
+ * Registers `func` (with `args`) as the function this debounce cycle
259
+ * will invoke, and (re)arms the debounce timer.
260
+ *
261
+ * Each call to `run()` accepts its own function — you are not locked
262
+ * into debouncing a single, fixed callback. If `run()` is called again
263
+ * before the pending timer fires, the previously-registered function
264
+ * and arguments are discarded entirely in favor of the new ones (a
265
+ * "last write wins" swap, not a queue).
266
+ *
267
+ * @example
268
+ * ```ts
269
+ * const { run } = useDebouncer(300);
270
+ *
271
+ * run((query: string) => fetchResults(query), searchTerm);
272
+ * ```
273
+ */
274
+ run: <Args extends unknown[]>(func: (...args: Args) => void, ...args: Args) => void;
275
+ /**
276
+ * Clears the pending timer and discards whatever function/arguments
277
+ * were registered via `run()`, without invoking anything. Sets
278
+ * `isPending` back to `false`.
279
+ */
280
+ cancel: () => void;
281
+ /**
282
+ * If a function is currently pending invocation, invokes it immediately
283
+ * (with its most recently registered arguments) and clears the timer.
284
+ * If nothing is pending, this is a no-op.
285
+ */
286
+ flush: () => void;
287
+ /**
288
+ * `true` whenever a trailing invocation is still scheduled to happen
289
+ * when the current cycle settles. `false` once it's known nothing
290
+ * further will fire — including immediately after a leading-edge
291
+ * invocation if `trailing` is disabled, not merely once the full window
292
+ * elapses.
293
+ */
294
+ isPending: boolean;
295
+ }
296
+ /**
297
+ * The debounce engine underlying every hook in this family.
298
+ *
299
+ * `useDebouncer` is a low-level scheduling primitive: a single timer and a
300
+ * single "next function to run" slot. Calling `run(func, ...args)`
301
+ * registers `func` as the occupant of that slot; if `run()` is called
302
+ * again before the timer fires, the new function/arguments replace the old
303
+ * ones outright.
304
+ *
305
+ * Most consumers won't reach for this directly — `useDebouncedCallback`,
306
+ * `useDebouncedState`, and `useDebouncedValue` are thin, purpose-built
307
+ * wrappers around it for the common cases (debouncing one fixed callback,
308
+ * a piece of state, or an incoming value). Use `useDebouncer` directly when
309
+ * you need the "swap, don't queue" behavior across genuinely different
310
+ * functions — see the example below.
311
+ *
312
+ * @example
313
+ * ```tsx
314
+ * function DocumentActionBar() {
315
+ * const { run, isPending } = useDebouncer(1000);
316
+ *
317
+ * const handleSave = () => run(() => saveDocument());
318
+ * const handleCancel = () => run(() => discardChanges());
319
+ *
320
+ * return (
321
+ * <>
322
+ * <button onClick={handleSave}>Save</button>
323
+ * <button onClick={handleCancel}>Cancel</button>
324
+ * {isPending && <span>Pending…</span>}
325
+ * </>
326
+ * );
327
+ * }
328
+ * ```
329
+ *
330
+ * @param delay - Milliseconds to wait before a trailing invocation fires.
331
+ * Coerced to a non-negative number; invalid input falls back to `0` with a
332
+ * dev-mode warning.
333
+ * @param options - See {@link DebounceOptions}.
334
+ * @returns See {@link UseDebouncerReturn}.
335
+ */
336
+ export declare function useDebouncer(delay: number, options?: DebounceOptions): UseDebouncerReturn;
337
+ /**
338
+ * Configuration for `useRateLimiter` and every hook built on top of it.
339
+ */
37
340
  export interface RateLimitOptions {
341
+ /**
342
+ * Called whenever a call is rejected because no executions remain in
343
+ * the current window.
344
+ *
345
+ * Safe to pass a fresh inline function on every render — it's captured
346
+ * in a ref and refreshed via effect, so it never causes the underlying
347
+ * timers to reset.
348
+ *
349
+ * @defaultValue `undefined`
350
+ */
38
351
  onRateLimitReached?: () => void;
352
+ /**
353
+ * Determines how the allowance replenishes once consumed.
354
+ *
355
+ * - `"burst"` — fixed window. All executions reset to the full `limit`
356
+ * at once, only once the entire `windowMs` duration has elapsed
357
+ * since the window began.
358
+ * - `"gradual"` — trickle refill. Executions return proportionately as
359
+ * time passes (`windowMs / limit` per execution), with no hard reset
360
+ * boundary.
361
+ *
362
+ * @defaultValue `"burst"`
363
+ */
39
364
  refillStrategy?: "burst" | "gradual";
40
365
  }
41
- export interface UseRateLimitReturn {
42
- run: <Args extends unknown[]>(func: (...args: Args) => void, ...args: Args) => void;
366
+ /**
367
+ * Options for `useRateLimitedState`: all of {@link RateLimitOptions}, plus
368
+ * an optional equality comparator used to skip committing a value
369
+ * equivalent to the one already held.
370
+ */
371
+ export type UseRateLimitedStateOptions<T> = RateLimitOptions & EqualityFnOption<T>;
372
+ /**
373
+ * Options for `useRateLimitedValue`: all of {@link RateLimitOptions}, plus
374
+ * an optional equality comparator used to skip committing a value
375
+ * equivalent to the one already held.
376
+ */
377
+ export type UseRateLimitedValueOptions<T> = RateLimitOptions & EqualityFnOption<T>;
378
+ /**
379
+ * The object returned by `useRateLimitedCallback`.
380
+ */
381
+ export interface UseRateLimitedCallbackReturn<Args extends unknown[]> {
382
+ /**
383
+ * A stable, rate-limited wrapper around `func`. Always invokes the
384
+ * most recently rendered `func`, even though `rateLimitedFunc`'s own
385
+ * identity doesn't change across re-renders.
386
+ *
387
+ * @returns `true` if `func` was invoked, `false` if the call was
388
+ * rejected because the allowance is exhausted.
389
+ */
390
+ rateLimitedFunc: (...args: Args) => boolean;
391
+ /** See {@link UseRateLimiterReturn.reset}. */
392
+ reset: () => void;
393
+ /** See {@link UseRateLimiterReturn.remaining}. */
43
394
  remaining: number;
395
+ /** See {@link UseRateLimiterReturn.isRateLimited}. */
44
396
  isRateLimited: boolean;
45
397
  }
46
- export declare function useRateLimit(limit: number, windowMs: number, options?: RateLimitOptions): UseRateLimitReturn;
47
- export interface UseRateLimitedCallbackReturn<Args extends unknown[]> {
48
- rateLimitedFunc: (...args: Args) => void;
398
+ /**
399
+ * Rate-limits a single function.
400
+ *
401
+ * `func` is captured in a ref and refreshed on every render — you can
402
+ * pass a fresh inline closure every time without resetting the
403
+ * underlying allowance tracking, and the wrapper always calls the
404
+ * *latest* `func`.
405
+ *
406
+ * @example
407
+ * ```tsx
408
+ * function SearchBox() {
409
+ * const { rateLimitedFunc, isRateLimited } = useRateLimitedCallback(
410
+ * (query: string) => fetch(`/api/search?q=${query}`),
411
+ * 10,
412
+ * 60_000,
413
+ * { refillStrategy: "gradual" },
414
+ * );
415
+ *
416
+ * return (
417
+ * <input
418
+ * disabled={isRateLimited}
419
+ * onChange={(e) => rateLimitedFunc(e.target.value)}
420
+ * />
421
+ * );
422
+ * }
423
+ * ```
424
+ *
425
+ * @param func - The function to rate-limit. Safe to pass a new closure
426
+ * on every render.
427
+ * @param limit - See {@link useRateLimiter}.
428
+ * @param windowMs - See {@link useRateLimiter}.
429
+ * @param options - See {@link RateLimitOptions}.
430
+ * @returns See {@link UseRateLimitedCallbackReturn}.
431
+ */
432
+ export declare function useRateLimitedCallback<Args extends unknown[]>(func: (...args: Args) => void, limit: number, windowMs: number, options?: RateLimitOptions): UseRateLimitedCallbackReturn<Args>;
433
+ /**
434
+ * The tuple returned by `useRateLimitedState`, mirroring `useState`'s
435
+ * `[value, setValue]` shape with a third element carrying rate-limit
436
+ * controls.
437
+ */
438
+ export type UseRateLimitedStateReturn<T> = [
439
+ /** The current, committed state value. */
440
+ T,
441
+ /**
442
+ * Attempts to update state. Accepts either a plain value or a
443
+ * `useState`-style functional updater (`(previous) => next`).
444
+ *
445
+ * Unlike the debounce/throttle `State` variants, nothing here is ever
446
+ * deferred — the update either applies immediately (against the
447
+ * genuinely current state, via React's own functional `setState`) or
448
+ * is rejected outright and state doesn't change at all. There's no
449
+ * "most recently scheduled value" to reason about, since nothing is
450
+ * ever queued.
451
+ *
452
+ * @returns `true` if the update was applied, `false` if it was
453
+ * rejected because the allowance is exhausted.
454
+ */
455
+ (value: T | ((previous: T) => T)) => boolean,
456
+ {
457
+ /** See {@link UseRateLimiterReturn.remaining}. */
458
+ remaining: number;
459
+ /** See {@link UseRateLimiterReturn.isRateLimited}. */
460
+ isRateLimited: boolean;
461
+ /** See {@link UseRateLimiterReturn.reset}. */
462
+ reset: () => void;
463
+ /**
464
+ * Bypasses rate-limit enforcement entirely and applies the value
465
+ * (or updater) immediately. Does not consume any of the allowance.
466
+ */
467
+ forceSetValue: (value: T | ((previous: T) => T)) => void;
468
+ }
469
+ ];
470
+ /**
471
+ * A `useState`-shaped hook whose setter can be rejected once the
472
+ * allowance for the current window is exhausted, instead of always
473
+ * applying.
474
+ *
475
+ * @example
476
+ * ```tsx
477
+ * function GenerationDemo() {
478
+ * const [result, generate, { remaining, isRateLimited }] =
479
+ * useRateLimitedState<string | null>(null, 3, 60_000);
480
+ *
481
+ * const handleGenerate = () => {
482
+ * if (!generate(`Result #${Math.random()}`)) {
483
+ * toast("Free limit reached — try again in a minute.");
484
+ * }
485
+ * };
486
+ *
487
+ * return (
488
+ * <>
489
+ * <button onClick={handleGenerate} disabled={isRateLimited}>
490
+ * Generate ({remaining} left)
491
+ * </button>
492
+ * <p>{result}</p>
493
+ * </>
494
+ * );
495
+ * }
496
+ * ```
497
+ *
498
+ * @param initialValue - Initial state value, or a `useState`-style lazy
499
+ * initializer function (`() => T`).
500
+ * @param limit - See {@link useRateLimiter}.
501
+ * @param windowMs - See {@link useRateLimiter}.
502
+ * @param options - See {@link UseRateLimitedStateOptions}.
503
+ * @returns See {@link UseRateLimitedStateReturn}.
504
+ */
505
+ export declare function useRateLimitedState<T>(initialValue: T | (() => T), limit: number, windowMs: number, options?: UseRateLimitedStateOptions<T>): UseRateLimitedStateReturn<T>;
506
+ /**
507
+ * The tuple returned by `useRateLimitedValue`.
508
+ */
509
+ export type UseRateLimitedValueReturn<T> = [
510
+ /** The rate-limited mirror of the source value. */
511
+ T,
512
+ {
513
+ /** See {@link UseRateLimiterReturn.remaining}. */
514
+ remaining: number;
515
+ /** See {@link UseRateLimiterReturn.isRateLimited}. */
516
+ isRateLimited: boolean;
517
+ /** See {@link UseRateLimiterReturn.reset}. */
518
+ reset: () => void;
519
+ }
520
+ ];
521
+ /**
522
+ * Mirrors `value`, but the mirror updates at most `limit` times per
523
+ * `windowMs` window.
524
+ *
525
+ * @remarks
526
+ * This has a meaningfully weaker guarantee than `useDebouncedValue` /
527
+ * `useThrottledValue`. Those hooks eventually deliver the *latest* value
528
+ * once their window settles, even if intermediate values were skipped.
529
+ * This hook does not — once the allowance is exhausted, incoming changes
530
+ * to `value` are dropped outright until the allowance refills, with no
531
+ * queueing and no catch-up. The mirror simply stays frozen at whatever it
532
+ * last committed until it's allowed to update again.
533
+ *
534
+ * @example
535
+ * ```tsx
536
+ * function NotificationFeed({ latestNotification }: { latestNotification: string }) {
537
+ * const [visibleNotification] = useRateLimitedValue(latestNotification, 3, 10_000);
538
+ *
539
+ * // At most 3 notifications surface per 10s window; any beyond that
540
+ * // are silently dropped rather than queued for later display.
541
+ *
542
+ * return <Toast message={visibleNotification} />;
543
+ * }
544
+ * ```
545
+ *
546
+ * @param value - The source value to rate-limit. Every change is subject
547
+ * to the current allowance.
548
+ * @param limit - See {@link useRateLimiter}.
549
+ * @param windowMs - See {@link useRateLimiter}.
550
+ * @param options - See {@link UseRateLimitedValueOptions}.
551
+ * @returns See {@link UseRateLimitedValueReturn}.
552
+ */
553
+ export declare function useRateLimitedValue<T>(value: T, limit: number, windowMs: number, options?: UseRateLimitedValueOptions<T>): UseRateLimitedValueReturn<T>;
554
+ /**
555
+ * The object returned by `useRateLimiter`.
556
+ */
557
+ export interface UseRateLimiterReturn {
558
+ /**
559
+ * Attempts to invoke `func` (with `args`) against the current
560
+ * allowance.
561
+ *
562
+ * Unlike `useDebouncer`/`useThrottler`, nothing here is ever deferred —
563
+ * every call to `run()` resolves synchronously, right now: either an
564
+ * execution is available and `func` runs immediately, or it isn't and
565
+ * `func` doesn't run at all (no queueing, no later catch-up).
566
+ *
567
+ * Each call accepts its own function, so a single `useRateLimiter`
568
+ * instance can gate several different actions against one shared
569
+ * allowance if needed.
570
+ *
571
+ * @returns `true` if `func` was invoked, `false` if the call was
572
+ * rejected because the current window's allowance is exhausted.
573
+ *
574
+ * @example
575
+ * ```ts
576
+ * const { run } = useRateLimiter(3, 10_000);
577
+ *
578
+ * const didFire = run(() => submitForm());
579
+ * if (!didFire) showToast("Too many attempts — please wait.");
580
+ * ```
581
+ */
582
+ run: <Args extends unknown[]>(func: (...args: Args) => void, ...args: Args) => boolean;
583
+ /**
584
+ * Immediately restores the full allowance and clears any in-progress
585
+ * background refill, bypassing the normal window/refill timing
586
+ * entirely. Useful after an unrelated event that should grant a fresh
587
+ * allowance outright — e.g. a successful CAPTCHA, or a plan upgrade.
588
+ */
589
+ reset: () => void;
590
+ /**
591
+ * The number of executions currently available. Kept accurate in real
592
+ * time — including while idle, with no further calls to `run()` —
593
+ * by a self-scheduling background timer that mirrors whichever
594
+ * `refillStrategy` is configured.
595
+ */
49
596
  remaining: number;
597
+ /** Convenience flag, equivalent to `remaining === 0`. */
50
598
  isRateLimited: boolean;
51
599
  }
52
- export declare function useRateLimitedCallback<Args extends unknown[]>(func: (...args: Args) => void, limit: number, windowMs: number, options?: RateLimitOptions): UseRateLimitedCallbackReturn<Args>;
600
+ /**
601
+ * The rate-limiting engine underlying every hook in this family.
602
+ *
603
+ * `useRateLimiter` grants up to `limit` executions per `windowMs` window,
604
+ * replenished according to `refillStrategy`. Unlike debounce or throttle,
605
+ * it never delays or reshapes *when* something runs — every call is an
606
+ * immediate accept-or-reject decision against the current allowance.
607
+ *
608
+ * Most consumers won't reach for this directly — `useRateLimitedCallback`,
609
+ * `useRateLimitedState`, and `useRateLimitedValue` are thin, purpose-built
610
+ * wrappers around it for the common cases.
611
+ *
612
+ * @example
613
+ * ```tsx
614
+ * function SubmitButton() {
615
+ * const { run, remaining, isRateLimited } = useRateLimiter(3, 10_000, {
616
+ * refillStrategy: "burst",
617
+ * onRateLimitReached: () => toast("Too many attempts."),
618
+ * });
619
+ *
620
+ * return (
621
+ * <button onClick={() => run(submitForm)} disabled={isRateLimited}>
622
+ * Submit ({remaining} left)
623
+ * </button>
624
+ * );
625
+ * }
626
+ * ```
627
+ *
628
+ * @param limit - Maximum executions allowed per window. Coerced to a
629
+ * non-negative integer with a floor of `1`; invalid input falls back to
630
+ * `1` with a dev-mode warning.
631
+ * @param windowMs - Length of the rate-limit window, in milliseconds.
632
+ * Coerced to a non-negative number; invalid input falls back to `0` with
633
+ * a dev-mode warning. A value of `0` disables rate limiting entirely
634
+ * (every call is allowed) rather than causing a division error — also
635
+ * dev-warned, since it's rarely intentional.
636
+ * @param options - See {@link RateLimitOptions}.
637
+ * @returns See {@link UseRateLimiterReturn}.
638
+ */
639
+ export declare function useRateLimiter(limit: number, windowMs: number, options?: RateLimitOptions): UseRateLimiterReturn;
640
+ /**
641
+ * Configuration for `useThrottler` and every hook built on top of it.
642
+ *
643
+ * @remarks
644
+ * `leading` and `trailing` may both be set to `false` at the same time —
645
+ * the hook will not silently correct this for you. That configuration
646
+ * means the throttled function will never run; a dev-mode warning is
647
+ * logged to help catch it early, but the choice itself is respected.
648
+ */
53
649
  export interface ThrottleOptions {
650
+ /**
651
+ * When `true`, invokes immediately on the first call of a new cooldown
652
+ * window.
653
+ *
654
+ * @defaultValue `true`
655
+ */
54
656
  leading?: boolean;
657
+ /**
658
+ * When `true`, invokes once more at the end of the cooldown window,
659
+ * using the most recently passed function/arguments — but only if at
660
+ * least one call arrived after the leading edge fired. A single
661
+ * isolated call with both edges enabled only fires once.
662
+ *
663
+ * @defaultValue `true`
664
+ */
55
665
  trailing?: boolean;
56
666
  }
57
- export interface UseThrottleReturn {
58
- run: <Args extends unknown[]>(func: (...args: Args) => void, ...args: Args) => void;
59
- cancel: () => void;
60
- flush: () => void;
61
- isPending: boolean;
62
- }
63
- export declare function useThrottle(delay: number, options?: ThrottleOptions): UseThrottleReturn;
667
+ /**
668
+ * Options for `useThrottledState`: all of {@link ThrottleOptions}, plus an
669
+ * optional equality comparator used to skip committing a value equivalent
670
+ * to the one already held.
671
+ */
672
+ export type UseThrottledStateOptions<T> = ThrottleOptions & EqualityFnOption<T>;
673
+ /**
674
+ * Options for `useThrottledValue`: all of {@link ThrottleOptions}, plus an
675
+ * optional equality comparator used to skip committing a value equivalent
676
+ * to the one already held.
677
+ */
678
+ export type UseThrottledValueOptions<T> = ThrottleOptions & EqualityFnOption<T>;
679
+ /**
680
+ * The object returned by `useThrottledCallback`.
681
+ */
64
682
  export interface UseThrottledCallbackReturn<Args extends unknown[]> {
683
+ /**
684
+ * A stable, throttled wrapper around `func`. Safe to attach directly
685
+ * to an event listener; internally always invokes the most recently
686
+ * rendered `func`, even though `throttledFunc`'s own identity doesn't
687
+ * change across re-renders.
688
+ */
65
689
  throttledFunc: (...args: Args) => void;
690
+ /** See {@link UseThrottlerReturn.cancel}. */
66
691
  cancel: () => void;
692
+ /** See {@link UseThrottlerReturn.flush}. */
67
693
  flush: () => void;
694
+ /** See {@link UseThrottlerReturn.isPending}. */
68
695
  isPending: boolean;
69
696
  }
697
+ /**
698
+ * Throttles a single function.
699
+ *
700
+ * `func` is captured in a ref and refreshed on every render — you can pass
701
+ * a fresh inline closure every time without resetting the running cooldown
702
+ * window, and the throttled wrapper always calls the *latest* `func`,
703
+ * closing over whatever props/state were current when it actually fires
704
+ * (never a stale closure from whenever the wrapper was first created).
705
+ *
706
+ * @example
707
+ * ```tsx
708
+ * function WindowSizeLogger() {
709
+ * const { throttledFunc: handleResize } = useThrottledCallback(
710
+ * () => console.log("width:", window.innerWidth),
711
+ * 200,
712
+ * );
713
+ *
714
+ * useEffect(() => {
715
+ * window.addEventListener("resize", handleResize);
716
+ * return () => window.removeEventListener("resize", handleResize);
717
+ * }, [handleResize]);
718
+ *
719
+ * return null;
720
+ * }
721
+ * ```
722
+ *
723
+ * @param func - The function to throttle. Safe to pass a new closure on
724
+ * every render.
725
+ * @param delay - See {@link useThrottler}.
726
+ * @param options - See {@link ThrottleOptions}.
727
+ * @returns See {@link UseThrottledCallbackReturn}.
728
+ */
70
729
  export declare function useThrottledCallback<Args extends unknown[]>(func: (...args: Args) => void, delay: number, options?: ThrottleOptions): UseThrottledCallbackReturn<Args>;
730
+ /**
731
+ * The tuple returned by `useThrottledState`, mirroring `useState`'s
732
+ * `[value, setValue]` shape with a third element carrying throttle
733
+ * controls.
734
+ */
71
735
  export type UseThrottledStateReturn<T> = [
736
+ /** The current (throttled) state value. */
72
737
  T,
73
- (value: T) => void,
738
+ /**
739
+ * Schedules a throttled update to state. Accepts either a plain value
740
+ * or a `useState`-style functional updater (`(previous) => next`).
741
+ *
742
+ * The functional-updater form composes correctly across multiple rapid
743
+ * calls made before the cooldown window settles — e.g. calling
744
+ * `setValue((p) => p + 1)` three times in a row schedules a cumulative
745
+ * `+3`, not three competing `+1`s racing to be "the" pending value.
746
+ * `previous` in that case refers to the most recently *scheduled*
747
+ * value, not necessarily the currently-committed state — this matters
748
+ * if you're chaining updates faster than the window settles.
749
+ */
750
+ (value: T | ((previous: T) => T)) => void,
74
751
  {
752
+ /** See {@link UseThrottlerReturn.isPending}. */
75
753
  isPending: boolean;
754
+ /**
755
+ * Cancels any pending throttled update. Also resyncs the internal
756
+ * "next value to commit" tracking back to the current committed
757
+ * state, so a subsequent functional update starts from the right
758
+ * baseline instead of building on a discarded value.
759
+ */
76
760
  cancel: () => void;
761
+ /** See {@link UseThrottlerReturn.flush}. */
77
762
  flush: () => void;
78
- forceSetValue: (value: T) => void;
763
+ /**
764
+ * Bypasses throttle scheduling entirely and applies the value (or
765
+ * updater) immediately. Also cancels any throttled update that was
766
+ * still pending, so it can't land afterward and silently overwrite
767
+ * this forced value.
768
+ */
769
+ forceSetValue: (value: T | ((previous: T) => T)) => void;
79
770
  }
80
771
  ];
81
- export declare function useThrottledState<T>(initialValue: T | (() => T), delay: number, options?: ThrottleOptions): UseThrottledStateReturn<T>;
82
- export type UseThrottledValueReturn<T> = T;
83
- export declare function useThrottledValue<T>(value: T, delay: number, options?: ThrottleOptions): UseThrottledValueReturn<T>;
772
+ /**
773
+ * A `useState`-shaped hook whose setter rate-limits its effect on state
774
+ * instead of applying immediately.
775
+ *
776
+ * @example
777
+ * ```tsx
778
+ * function ScoreBoard() {
779
+ * const [score, setScore, { flush, forceSetValue, isPending }] =
780
+ * useThrottledState(() => expensiveInitialScore(), 500);
781
+ *
782
+ * return (
783
+ * <>
784
+ * <p>Score: {score}</p>
785
+ * <button onClick={() => setScore((s) => s + 1)}>+1 (throttled)</button>
786
+ * <button onClick={flush}>Flush pending update</button>
787
+ * <button onClick={() => forceSetValue(0)}>Reset instantly</button>
788
+ * {isPending && <span>update queued…</span>}
789
+ * </>
790
+ * );
791
+ * }
792
+ * ```
793
+ *
794
+ * @param initialValue - Initial state value, or a `useState`-style lazy
795
+ * initializer function (`() => T`).
796
+ * @param delay - See {@link useThrottler}.
797
+ * @param options - See {@link UseThrottledStateOptions}.
798
+ * @returns See {@link UseThrottledStateReturn}.
799
+ */
800
+ export declare function useThrottledState<T>(initialValue: T | (() => T), delay: number, options?: UseThrottledStateOptions<T>): UseThrottledStateReturn<T>;
801
+ /**
802
+ * The tuple returned by `useThrottledValue`.
803
+ */
804
+ export type UseThrottledValueReturn<T> = [
805
+ /** The throttled (rate-limited) mirror of the source value. */
806
+ T,
807
+ {
808
+ /** See {@link UseThrottlerReturn.isPending}. */
809
+ isPending: boolean;
810
+ /** Cancels the pending sync to the latest source value. */
811
+ cancel: () => void;
812
+ /** Immediately commits the latest source value, bypassing the wait. */
813
+ flush: () => void;
814
+ }
815
+ ];
816
+ /**
817
+ * Mirrors `value`, but the mirror updates at most once every `delay`
818
+ * milliseconds — a safe, rate-limited dependency for an expensive
819
+ * downstream render (chart, canvas, map) driven by a fast-changing source
820
+ * like a slider or live coordinates.
821
+ *
822
+ * @remarks
823
+ * With the default `{ leading: true }`, the mirror updates almost
824
+ * immediately on the first change — throttle is about limiting *rate*,
825
+ * not deferring the first response the way debounce does.
826
+ *
827
+ * @example
828
+ * ```tsx
829
+ * function SliderDemo() {
830
+ * const [raw, setRaw] = useState(0);
831
+ * const [throttled] = useThrottledValue(raw, 100);
832
+ *
833
+ * return (
834
+ * <>
835
+ * <input
836
+ * type="range"
837
+ * value={raw}
838
+ * onChange={(e) => setRaw(Number(e.target.value))}
839
+ * />
840
+ * <HeavyPreview value={throttled} />
841
+ * </>
842
+ * );
843
+ * }
844
+ * ```
845
+ *
846
+ * @param value - The source value to throttle. Every change is subject to
847
+ * the cooldown window.
848
+ * @param delay - See {@link useThrottler}.
849
+ * @param options - See {@link UseThrottledValueOptions}.
850
+ * @returns See {@link UseThrottledValueReturn}.
851
+ */
852
+ export declare function useThrottledValue<T>(value: T, delay: number, options?: UseThrottledValueOptions<T>): UseThrottledValueReturn<T>;
853
+ /**
854
+ * The object returned by `useThrottler`.
855
+ */
856
+ export interface UseThrottlerReturn {
857
+ /**
858
+ * Registers `func` (with `args`) as the function this cooldown window
859
+ * will invoke.
860
+ *
861
+ * Each call to `run()` accepts its own function — you are not locked
862
+ * into throttling a single, fixed callback. If a trailing invocation is
863
+ * still pending when `run()` is called again, the previously-registered
864
+ * function and arguments are replaced by the new ones — whichever call
865
+ * was most recent before the window closes is the one that fires (a
866
+ * "last write wins" swap, not a queue).
867
+ *
868
+ * @example
869
+ * ```ts
870
+ * const { run } = useThrottler(200);
871
+ *
872
+ * run((x: number, y: number) => logPosition(x, y), clientX, clientY);
873
+ * ```
874
+ */
875
+ run: <Args extends unknown[]>(func: (...args: Args) => void, ...args: Args) => void;
876
+ /**
877
+ * Clears any pending trailing invocation and resets the cooldown
878
+ * window entirely — the next call to `run()` is treated as the start
879
+ * of a fresh window. Sets `isPending` back to `false`.
880
+ */
881
+ cancel: () => void;
882
+ /**
883
+ * If a trailing invocation is currently pending, invokes it
884
+ * immediately (with its most recently registered arguments) and clears
885
+ * the timer. If nothing is pending, this is a no-op.
886
+ */
887
+ flush: () => void;
888
+ /**
889
+ * `true` whenever a trailing invocation is still scheduled to fire
890
+ * before the current cooldown window closes. `false` once it's known
891
+ * nothing further will happen — including right after a leading-edge
892
+ * invocation with no follow-up call yet, not merely once the whole
893
+ * window elapses.
894
+ */
895
+ isPending: boolean;
896
+ }
897
+ /**
898
+ * The throttle engine underlying every hook in this family.
899
+ *
900
+ * `useThrottler` is a low-level scheduling primitive: a single cooldown
901
+ * window and a single "next function to run" slot. Unlike debounce,
902
+ * additional calls that arrive mid-window do not push the window out
903
+ * further — they just update which function/arguments will fire when the
904
+ * *existing* window closes. This is what keeps a continuous stream of
905
+ * calls (mousemove, scroll, resize) firing at a steady cadence instead of
906
+ * only ever firing once activity stops.
907
+ *
908
+ * Most consumers won't reach for this directly — `useThrottledCallback`,
909
+ * `useThrottledState`, and `useThrottledValue` are thin, purpose-built
910
+ * wrappers around it for the common cases. Use `useThrottler` directly
911
+ * when you need the "swap, don't queue" behavior across genuinely
912
+ * different functions.
913
+ *
914
+ * @example
915
+ * ```tsx
916
+ * function ActivityLogger() {
917
+ * const { run, isPending } = useThrottler(1000);
918
+ *
919
+ * return (
920
+ * <div
921
+ * onMouseMove={(e) => run(logMouseMove, e.clientX, e.clientY)}
922
+ * onKeyDown={(e) => run(logKeyPress, e.key)}
923
+ * >
924
+ * {isPending ? "Recording…" : "Idle"}
925
+ * </div>
926
+ * );
927
+ * }
928
+ * ```
929
+ *
930
+ * @param delay - Length of the cooldown window, in milliseconds. Coerced
931
+ * to a non-negative number; invalid input falls back to `0` with a
932
+ * dev-mode warning.
933
+ * @param options - See {@link ThrottleOptions}.
934
+ * @returns See {@link UseThrottlerReturn}.
935
+ */
936
+ export declare function useThrottler(delay: number, options?: ThrottleOptions): UseThrottlerReturn;
84
937
  export type ScrollAlign = "start" | "center" | "end" | "auto";
85
938
  export type Axis = "vertical" | "horizontal";
86
939
  export interface ScrollToOffsetOptions {