简体   繁体   中英

React useEffect causing infinite re-render despite passing argument to dependency array

The 'myPosts' has an object with multiple posts inside it.. I wanted the user profile to immediately show the post after it is uploaded so I passed 'myposts' in the dependency array.

But the problem is that the component is re-rendering infinitely. How can I make it so that it re-renders once, only when a new post is uploaded? I can't understand why passing 'myposts' in the array is causing infinite renders instead of only once.

  const [myposts, setPosts] = useState([]);
  useEffect(() => {
  fetch('/mypost', {
    headers: {
     cookie: 'access_key',
    },
   })
     .then((res) => res.json())
     .then((data) => {
     // console.log(data);
     setPosts(data.myposts);
  });
 }, [myposts]);

When fetch resolves, it modifies myposts , which triggers a fetch because it is listed as dependency of useEffect, which modifies myposts , and so it continues...

It seems that myposts depends on the result of the fetch, not the other way around. So I would suggest removing myposts from the dependency list.

The useEffect hook is called when myposts gets updated. In the final .then of your fetch, you're updating it via setPosts . The best way to fix this is by making the dependency array an empty array.
But this won't solve the issue of updating posts from the server, but this can also be done in a periodic function with setInterval . This would result in something like the code below.

const [myposts, setPosts] = useState([]);

const update = fetch('/mypost', {
  headers: {
    cookie: 'access_key',
  },
})
.then((res) => res.json())
.then((data) => {
  // console.log(data);
  setPosts(data.myposts);
});

useEffect(() => {
  update()
  const interval = setInterval(update, 30000)
  return () => clearInterval(interval)
}, []);

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