score:5

Accepted answer

this is because you passed an array containing your products state, rather than an empty array, which will fire useeffect on state change (for products state specifically). try changing your code to an empty array:

useeffect(() => {
const getproducts = async () => {
  return await axios
    .get('/getallproducts')
    .then((response) => {
      setproducts(response.data);
      console.log(products);
    })
    .catch((e) => {
      console.log(e);
    });
  };
  getproducts();
  }, []);

as @skyboyer mentioned below, it is good to note that state is not updated in a synchronous manner. therefor, console.log(products) will not reflect an accurate value for your state when useeffect runs.

it is okay to use multiple useeffect hooks. if you would like to view your updated state in the console, or do some other work with it, you could add another useeffect hook and pass your state into the array:

useeffect(() => {
    console.log(products);
}, [products]);

score:1

since products is in the useeffect dependency array, it is going to run every time there are changes made to the products state. getproducts() runs setproducts which then in turn is going to trigger the use effect again. using an empty array in the useeffect will tell it to only run when the component is mounted.

like this:

useeffect(() => {
const getproducts = async () => {
  return await axios
    .get('/getallproducts')
    .then((response) => {
      setproducts(response.data);
      console.log(products);
    })
    .catch((e) => {
      console.log(e);
    });
  };
  getproducts();
  }, []);

Related Query

More Query from same tag