I call following function within useEffect
.
useEffect(() => {
loadData();
}, [amount]);
loadData
function uses Lodash debounce
function. When I update amount from input, loadData
gets called several times depending on length of amount
string.
const loadData = useCallback(
debounce(() => {
console.log('called!');
// Fetch data from API ...
}, 1000),
[amount]
);
In spite of using useCallback
hook and 1s debounce. It returns multiple times. How to fix it?
Thanks in advance
CodePudding user response:
When amount
changes, the useCallback
generates a new function with a new debounce timer. To solve that pass amount
a parameter to the function, and remove amount
from the deps array of the useCallback
:
const loadData = useCallback(
debounce((amount) => {
console.log('called!', amount);
// Fetch data from API ...
}, 1000),
[]
);
useEffect(() => {
loadData(amount);
}, [amount]);