简体   繁体   中英

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]);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM