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
475 views
in Technique[技术] by (71.8m points)

reactjs - Infinite loop with useEffect

Why is the following giving me an infinite rerender? I have a small component with a single useEffect. Does the second param [currentData] do shallow comparison or something ?

useEffect(() => {
    getMyData().then(({ data }) => {
      setData({ ...currentData }, { data });
    });
  }, [currentData]);
question from:https://stackoverflow.com/questions/65895721/infinite-loop-with-useeffect

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

1 Answer

0 votes
by (71.8m points)

It because when you use ({...currentData}) you literally create a new object, a new reference to a new object, and Javascript compare objects by reference, not value. So the new value of currentData will always different from the previous once. That make the flow would look like this:

You setData (create new Object) => useEffect detect that currentData changed => it run into the call back, subscribe again => You setData (create new Object) again => useEffect detect that currentData changed . And that cause the loop.

Currently, comparing deep nested object is not supported in React useEffect. But you can overcome the issue using a custom hook, i found another answer that I think could help


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

...