I am fetching a data from an API and setting a state. When I do that process, It makes get requests each millisecond. This problem happens, if I set the dependencies array. I want to make a request when API is updated.
const [products, setProducts] = useState({ baskets: [] });
useEffect(() => {
fetch("/api")
.then((response) => response.json())
.then((products) => {
setProducts(products);
});
}, [products]);
3
Answers
Remove the dependency from the useEffect Hook
Here you are updating results into setProducts and it triggers products state change due to useEffect behaviour, So it’ll be called infinety.
Also I suggest you to change
Here, you’ll face issues with scope in products.
So your final could should be this :
Also As per your below comment, here is the updated sample code with use of useCallback
** call fetchProdcuts method whenever you need to refresh the product lists**
Hope it helps!
You’re trying to fetch data from the API and update
products
with the API response. The implementation is correct, but it’s causing an infinite loop.The loop occurs because the useEffect dependency array includes
products
, signifying that the useEffect should be triggered wheneverproducts
change.Here’s how the loop unfolds:
products.
in the dependency array), causing it to run again.
To break this loop, you should remove
products
from the useEffect dependency array. By doing so, the useEffect will execute only when the component mounts, avoiding subsequent triggers caused by state changesYou can read more about useEffects in the docs.
Try like this