I need to access variables in a useEffect
but only trigger the method when SOME of them get updated.
For example:
I want to call useEffect when data
changes, but NOT when saveTimeout
or saveMethod
change.
In the same fashion, I want to call saveMethod
when my component dismounts, but I can't because it needs to be in the dependency array, therefore calling it at every change of saveMethod
.
function SavingComponent({data, apiInfo}){
[saveTimeout, setSaveTimeout] = useState(null);
const saveMethod = useCallBack(()=>{
clearTimeout(saveTimeout);
// api call to save the data using apiInfo
}, [data, saveTimeout, apiInfo])
// Start a timer to save the data 2 seconds after it is changed (not working)
useEffect(()=>{
clearTimeout(saveTimeout);
setSaveTimeout(setTimeout(saveMethod, 2000));
}, [data, saveTimeout, saveMethod]);
// Save immediately on dismount only (not working)
useEffect(()=>{
return ()=> { saveMethod(); }
},[saveMethod])
return (// some rendering)
}
This is an issue I am constantly running into with other cases and have to hack around. Usually using a custom usePrevious
method. I would compare the previous value of the prop to the current and return immediately if the prop I am interested in didn't change.
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
What is the proper way to only call useEffect
when SOME dependencies get updated?