Last active
July 16, 2021 16:41
-
-
Save olayemii/7fef5c03825b40a4090c00ac2d502a79 to your computer and use it in GitHub Desktop.
useDebounce - A hook to debounce a function
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 { useEffect, useCallback } from "react"; | |
let debounceTimeout; | |
const useDebounce = (delay = 1000) => { | |
const debounceRequest = useCallback( | |
debounceFunction => { | |
clearTimeout(debounceTimeout); | |
debounceTimeout = setTimeout(() => { | |
debounceFunction(); | |
}, delay); | |
}, | |
[delay] | |
); | |
useEffect(() => { | |
return () => clearTimeout(debounceTimeout); | |
}, [debounceRequest]); | |
return [debounceRequest]; | |
}; | |
export default useDebounce; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To use this hook
useDebounce
to your component.debouncer(() =>console.log(1+1))
//the result will be logged after 1000msMOTIVATION This was made to delay server calls when making searches, instead of making a request on every keystroke, we debounce to a delayed time after the last keystroke.