Created
July 5, 2020 20:40
-
-
Save maurocen/efeb535ac332372cbf6ff8e904c84a97 to your computer and use it in GitHub Desktop.
A hook to debounce events
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 } from 'react'; | |
const useDebounce = () => { | |
const [timer, setTimer] = useState(null); | |
const debounce = (callback, time) => (e) => { | |
e.persist(); | |
if (timer) { | |
clearTimeout(timer); | |
} | |
const timeout = setTimeout(() => { | |
callback(e); | |
setTimer(null); | |
}, time); | |
setTimer(timeout); | |
} | |
return debounce; | |
}; | |
export default useDebounce; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment