I\'m trying to use the throttle method from lodash in a functional component, e.g.:
const App = () => {
const [value, setValue
Here's a simple hook to debounce your calls.
To use the below code, all you have to do is declare it as so
const { debounceRequest } = useDebounce(someFn);
And, then call it as so
debounceRequest();
Implementation is shown below
import React from "react";
const useDebounce = (callbackFn: () => any, timeout: number = 500) => {
const [sends, setSends] = React.useState(0);
const stabilizedCallbackFn = React.useCallback(callbackFn, [callbackFn]);
const debounceRequest = () => {
setSends(sends + 1);
};
// 1st send, 2nd send, 3rd send, 4th send ...
// when the 2nd send comes, then 1st set timeout is cancelled via clearInterval
// when the 3rd send comes, then 2nd set timeout is cancelled via clearInterval
// process continues till timeout has passed, then stabilizedCallbackFn gets called
// return () => clearInterval(id) is critical operation since _this_ is what cancels
// the previous send.
// *