Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React / Axios send infinite number of requests

I'm fetching data from my backend api when component mount and can do it successfuly but my React app keeps sending requests to the server causing it to slow down. I used useEffect hook, but I'm getting the same result without using the hook.

useEffect(() => {
   axios.get('http://127.0.0.1:8000/food_category/')
  .then(response => {
   setFoodCategory(response.data);
   console.log(response.data);
})});

What am I doing wrong?

like image 840
Renato Maretić Avatar asked Oct 22 '25 06:10

Renato Maretić


1 Answers

If you give no dependencies to the useEffect hook, it will execute every time your component renders (which will happen infinitely because you set the state after getting data and thus your component rerenders).

Check out the second argument of useEffect in the docs to learn more about it.

An empty dependencies array indicates the useEffect will act as a mount and only executes once.

useEffect(() => {
    // Do mount stuff here such as executing your request.
}, []);
like image 195
ApplePearPerson Avatar answered Oct 23 '25 19:10

ApplePearPerson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!