Skip to content

Instantly share code, notes, and snippets.

@madflanderz
Created February 20, 2019 15:05
Show Gist options
  • Save madflanderz/d64d7d726f131f8b74164b8bf8b5d966 to your computer and use it in GitHub Desktop.
Save madflanderz/d64d7d726f131f8b74164b8bf8b5d966 to your computer and use it in GitHub Desktop.
useDebounce hook
import { useState, useEffect } from 'react'
const useDebounce = (fn: () => any, ms: number = 0, args: any[] = []) => {
const [timeout, setTimeoutVar] = useState<any>(null)
const [isStart, setStart] = useState(true)
useEffect(() => {
// don't start interval when executed first time
if (isStart) {
setStart(false)
return
}
// if args change then clear timeout
clearTimeout(timeout)
const t = setTimeout(fn.bind(null, args), ms)
setTimeoutVar(t)
}, args)
}
export default useDebounce
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment