Reputation: 8420
I have this effect:
React.useEffect(() => {
if (!maximumTocAttemptsExceeded) {
if (!isLoading) {
console.log('Here I need to reach');
}
}
}, [isLoading, error]);
My doubt is:
If error
value (that comes as a prop each time that the component is rendered) changes, will the useEffect get executed? But I'm not using its value inside the useEffect. And, maximumTocAttemptsExceeded
comes from props too, do I need to put it as a dependency on the hook?
My useEffect is being triggered way more times than I need it. It's supposed to be executed only when error is defined
Upvotes: 0
Views: 356
Reputation: 31385
If this is the effect you need to run:
if (!maximumTocAttemptsExceeded) {
if (!isLoading) {
console.log('Here I need to reach');
}
}
You should add only maximumTocAttemptsExceeded
and isLoading
to your dependency array.
Why?
Because React will always keep your effects up-to-date. So if you are using those variables, React assumes that if one of those variables change, it should re-run your effect code so you'll get an up-to-date effect on your component.
If error
has got anything to do to your effect code, you should use it and add it to the dependency array as well.
Example:
React.useEffect(() => {
if (error) {
if (!maximumTocAttemptsExceeded) {
if (!isLoading) {
console.log('Here I need to reach');
}
}
}
}, [isLoading, error,maximumTocAttemptsExceeded]);
Be aware that React does only shallow comparisons on those reference values. So if any of the variables in the dependency array is an object or array which is being recreated on every render, your effect will run on every render. Because although the content of those objects could be the same from previous render, their references change when they are recreated. So, if you your effect depends on a property of an object, you should use only that, and add it to the dependency array as obj.prop
, so React will know that you depend on a single prop
of the object instead of the whole object.
Upvotes: 1