Skip to content

Instantly share code, notes, and snippets.

@fmartins-andre
Created October 24, 2022 16:25
Show Gist options
  • Save fmartins-andre/5d14ca7915d08519b02873c6b0524d08 to your computer and use it in GitHub Desktop.
Save fmartins-andre/5d14ca7915d08519b02873c6b0524d08 to your computer and use it in GitHub Desktop.
Debounce a React.js function
import { DebouncedFunc } from "lodash"
import debounce from "lodash.debounce"
import { useMemo } from "react"
export default function useDebouncedFn<T extends (...args: any[]) => void>(fn: T, wait?: number) {
return useMemo(() =>(
debounce((...args:any[]) => {fn(...args)}, wait ?? 300) as DebouncedFunc<T>
), [fn, wait])
}
@fmartins-andre
Copy link
Author

const wait = 800;

function myFn() {
  console.log('My Function');
}

useDebouncedFn(myFn, wait)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment