it would be best to first look at my code:
import React, { Component } from \'react\';
import _ from \'lodash\';
import Services from \'Services\'; // Webser
Solution for those who came here because throttle / debounce doesn't work with FunctionComponent
- you need to store debounced function via useRef():
export const ComponentName = (value = null) => {
const [inputValue, setInputValue] = useState(value);
const setServicesValue = value => Services.setValue(value);
const setServicesValueDebounced = useRef(_.debounce(setServicesValue, 1000));
const handleChange = ({ currentTarget: { value } }) => {
setInputValue(value);
setServicesValueDebounced.current(value);
};
return ;
};
This medium article perfectly explains what happens:
Local variables inside a function expires after every call. Every time the component is re-evaluated, the local variables gets initialized again. Throttle and debounce works using
window.setTimeout()
behind the scenes. Every time the function component is evaluated, you are registering a freshsetTimeout
callback. So we will useuseRef()
hook as value returned byuseRef()
does not get re-evaluated every time the functional component is executed. The only inconvenience is that you have to access your stored value via the.current
property.
I've created sandbox with tiny lodash.throttle
and lodash.debounce
packages so you can experiment with both and choose suitable behavior