Created
October 26, 2020 00:53
-
-
Save SangeetAgarwal/4f6f8ff7226b7471788a5e57fffb217c to your computer and use it in GitHub Desktop.
debounce as xhr call using hooks
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 React from "react"; | |
const useDebounce = (callbackFn: () => any | Promise<any> , timeout: number = 500) => { | |
const [sends, setSends] = React.useState(0); | |
const debounceRequest = () => { | |
setSends(sends + 1); | |
}; | |
React.useEffect(() => { | |
if (sends > 0) { | |
const id = window.setTimeout(() => { | |
callbackFn(); | |
setSends(0) | |
}, timeout); | |
return () => { | |
return window.clearInterval(id); | |
}; | |
} | |
}, [callbackFn, sends, timeout]); | |
return { | |
debounceRequest, | |
}; | |
}; | |
export default useDebounce; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment