Created
February 20, 2019 15:05
-
-
Save madflanderz/d64d7d726f131f8b74164b8bf8b5d966 to your computer and use it in GitHub Desktop.
useDebounce hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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