(frontend) create hook for rate-limiting functions that could spam UI

Implement custom hook to throttle JavaScript function calls and prevent
interface performance degradation.
This commit is contained in:
lebaudantoine
2025-04-28 19:38:54 +02:00
committed by aleb_the_flash
parent 0c811222d4
commit 978d931bd7

View File

@@ -0,0 +1,37 @@
import { useCallback, useRef } from 'react'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type RateLimiterProps<T extends (...args: any[]) => any> = {
callback: T
maxCalls: number
windowMs: number
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function useRateLimiter<T extends (...args: any[]) => any>({
callback,
maxCalls = 5,
windowMs = 1000,
}: RateLimiterProps<T>) {
const callsCountRef = useRef(0)
const resetTimeoutRef = useRef<NodeJS.Timeout | undefined>(undefined)
const rateLimitedFn = useCallback(
(...args: Parameters<T>) => {
if (callsCountRef.current < maxCalls) {
callsCountRef.current += 1
if (callsCountRef.current === 1) {
resetTimeoutRef.current = setTimeout(() => {
callsCountRef.current = 0
resetTimeoutRef.current = undefined
}, windowMs)
}
return callback(...args)
} else {
return null
}
},
[callback, maxCalls, windowMs]
)
return rateLimitedFn
}