Inside my React component, I have these:
const [vendor,setVendor] = useState("");
const [taggedWith,setTaggedWith] = useState("");
function updateQuery () {
const filters = [];
if(vendor) {
filters.push({
label: `Vendor: ${vendor}`
})
}
if(taggedWith) {
filters.push({
label: `Tagged with: ${taggedWith}`
})
}
props.onUpdate(filters);
}
function debounce (func,delay){
let timer;
return function () {
clearTimeout(timer);
timer = setTimeout(()=>{
func();
},delay);
};
};
const updateQueryWithDebounce = useCallback(debounce(updateQuery,300),[]);
useEffect(()=>{
updateQueryWithDebounce();
},[taggedWith,vendor]);
Debouncing works, but the problem is, the stateful variables inside updateQuery function stays the same, because of useCallback. If I pass those states to the dependency array of useCallback, the debouncing function gets redeclared at every render, thus, new function with its closure is created which leads to debouncing not working. How can I fix that ?