Skip to content

Instantly share code, notes, and snippets.

@SangeetAgarwal
Created October 26, 2020 00:53
Show Gist options
  • Save SangeetAgarwal/4f6f8ff7226b7471788a5e57fffb217c to your computer and use it in GitHub Desktop.
Save SangeetAgarwal/4f6f8ff7226b7471788a5e57fffb217c to your computer and use it in GitHub Desktop.
debounce as xhr call using hooks
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