简体   繁体   中英

useEffect causing an infinite render loop

I'm using react useEffect to get data from my backend, but it spams my terminal with the same message non-stop.

My code

function DataFetching() {

    let [posts, setPosts] = useState([]); 

    useEffect(() => {
        axios.get('http://localhost:8080/zoom')
            .then(res => {
                setPosts(res.data);
            })
            .catch(err => {
                console.log(err)
            })
    })

The spam message I get on terminal

Executing (default): SELECT `id`, `subject`, `MEETINGID`, `Password`, `createdAt`, `updatedAt` FROM `data` AS `data`;```

setPosts() is causing DataFetching to re-render, and because your useEffect() doesn't declare a dependencies list, it evaluates the effect after every render, so you've essentially coded an asynchronous infinite loop.

Your effect only depends on setPosts() , so you should declare that as the only dependency. Or, recognizing that setPosts() is already memoized by React, declare no dependencies at all:

useEffect(() => {
  axios.get('http://localhost:8080/zoom').then(res => {
    setPosts(res.data);
  }).catch(err => {
    console.log(err);
  });
}, [/*setPosts*/]);

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