Reputation: 75
Error: Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.
const [products, setProducts] = useState([]);
useEffect(() => {
setProducts(getCartProducts());
}, [products]);
When passing an empty array as the second argument, the app works fine but in order to reflect the changes on the page I have to refresh it, but after passing the 'items' object as the second argument in the array, I receive the above error.
Upvotes: 1
Views: 1389
Reputation: 667
const [products, setProducts] = useState([]);
useEffect(() => {
setProducts(getCartProducts());
}, [products]);
This is equivalent to setting state inside componentDidUpdate without any conditions.
You are updating your state inside useEffect
that is correct but passing your same state inside dependency array
as an argument which will be updated inside your effect is wrong
. You should set change your dependency injection and you should re-evaluate your code and mark your dependency array accordingly. If you are setting products
as your effect's dependency array then your are just saying to react that run this effect whenever products
updated and inside effect you are just updating products
, so it does not make any sense, one thing you can do is use an auxiliary state for running your effect.
Upvotes: 2
Reputation: 106
Calling setItems
(you meant setProducts
, right?) in the useEffect
, forces products
state to be updated, which then forces useEffect
to be called.
By passing [products]
as a second argument you watch for the changes made on this field. And the value of products
changes. I guess it's because getCartProducts()
produces new reference (is non-primitive, like a object, or an array). That's why React thinks the field has changed.
That forms a loop.
Upvotes: 0