|
| 1 | +import { useMemo } from 'react'; |
| 2 | +import useLatest from '../useLatest'; |
| 3 | +import useUnmount from '../useUnmount'; |
| 4 | +import { isFunction } from '../utils'; |
| 5 | +import isDev from '../utils/isDev'; |
| 6 | + |
| 7 | +type noop = (...args: any[]) => any; |
| 8 | + |
| 9 | +export interface RateLimitOptions { |
| 10 | + wait?: number; |
| 11 | + leading?: boolean; |
| 12 | + trailing?: boolean; |
| 13 | + maxWait?: number; |
| 14 | +} |
| 15 | + |
| 16 | +export interface RateLimitFunction<T extends noop> { |
| 17 | + (...args: Parameters<T>): ReturnType<T>; |
| 18 | + cancel: () => void; |
| 19 | + flush: () => void; |
| 20 | +} |
| 21 | + |
| 22 | +export function createRateLimitFn<T extends noop>( |
| 23 | + rateLimitFn: ( |
| 24 | + func: (...args: Parameters<T>) => ReturnType<T>, |
| 25 | + wait: number, |
| 26 | + options?: RateLimitOptions, |
| 27 | + ) => RateLimitFunction<T>, |
| 28 | + hookName: string, |
| 29 | +) { |
| 30 | + return function useRateLimitFn(fn: T, options?: RateLimitOptions) { |
| 31 | + if (isDev) { |
| 32 | + if (!isFunction(fn)) { |
| 33 | + console.error(`${hookName} expected parameter is a function, got ${typeof fn}`); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + const fnRef = useLatest(fn); |
| 38 | + |
| 39 | + const wait = options?.wait ?? 1000; |
| 40 | + |
| 41 | + // Note: We intentionally use an empty dependency array here. |
| 42 | + // The rateLimitFn is created once and captures the latest fn via fnRef.current |
| 43 | + // eslint-disable-next-line react-hooks/exhaustive-deps |
| 44 | + const rateLimited = useMemo( |
| 45 | + () => |
| 46 | + rateLimitFn( |
| 47 | + (...args: Parameters<T>): ReturnType<T> => { |
| 48 | + return fnRef.current(...args); |
| 49 | + }, |
| 50 | + wait, |
| 51 | + options, |
| 52 | + ), |
| 53 | + // biome-ignore lint/correctness/useExhaustiveDependencies: rateLimitFn is stable, fnRef updates are captured via .current |
| 54 | + [], |
| 55 | + ); |
| 56 | + |
| 57 | + useUnmount(() => { |
| 58 | + rateLimited.cancel(); |
| 59 | + }); |
| 60 | + |
| 61 | + return { |
| 62 | + run: rateLimited, |
| 63 | + cancel: rateLimited.cancel, |
| 64 | + flush: rateLimited.flush, |
| 65 | + }; |
| 66 | + }; |
| 67 | +} |
0 commit comments