Skip to content

Instantly share code, notes, and snippets.

@christianvmm
Created August 6, 2023 05:53
Show Gist options
  • Select an option

  • Save christianvmm/46d3637baf83f0c4b663e45dada97f8e to your computer and use it in GitHub Desktop.

Select an option

Save christianvmm/46d3637baf83f0c4b663e45dada97f8e to your computer and use it in GitHub Desktop.
useDebounce.ts
import { useRef } from 'react'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useDebounce<T extends (...params: any[]) => void>(
fn: T,
delay = 1000
) {
const debounceRef = useRef<ReturnType<typeof setTimeout>>()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return function (this: any, ...args: any[]) {
if (debounceRef.current) {
clearTimeout(debounceRef.current)
}
debounceRef.current = setTimeout(() => {
fn.apply(this, args)
}, delay)
} as T
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment