Home > Blockchain >  how can I fix the "Too many re-renders. React limits the number of renders to prevent an infini
how can I fix the "Too many re-renders. React limits the number of renders to prevent an infini

Time:12-16

I'm trying to loop through an object and add up the numbers in there.

  const [cartCount, setCartCount] = useState(0)

  for (let i = 1; i <= Object.keys(cartItems).length; i  ) { //cartItems is the object
     setCartCount(cartCount   cartItems[i])
  }

but any attempt to update the state throws me the too many renders error. So how can I fix this?

CodePudding user response:

the reason of error is that you re-render the state in a loop. lets mutate your data then update state.

  const [cartCount, setCartCount] = useState(0)

  const handle = ()=>{
  let newCount = cartCount;

  for (let i = 1; i <= Object.keys(cartItems).length; i  ) { 
  
  newCount = cartCount   cartItems[i];
 }
 setCartCount(newCount)
 }

CodePudding user response:

This will only set your state once, and will not make your app re-render

const [cartCount, setCartCount] = useState(0)

useEffect(() => {

  const count = 0
  for (let i = 1; i <= Object.keys(cartItems).length; i  ) { //cartItems is the object
    count  = cartItems[i]
  }
  setCartCount(count)
}, [])

  • Related