Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

reactjs - React useEffect deps being called

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

question from:https://stackoverflow.com/questions/65947904/react-useeffect-deps-being-called

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...