score:0

Putting [firebase, cartItems] tells react to always re-render if any change is made to these two parametres. So that is why there are too many re-renders.

score:3

use blank [] instead of [firebase, cartItems]

score:3

The below code should work for you:

const cartItems = useItems();
// I assume this gives you cartItems.

let [total, updateTotal] = useState(() => {
  if (cartItems) {
    // item object {id: "2", name: "Cucumber", category: "vegetable", price: 50, // //count: 0}
    return cartItems.reduce((acc, elem) => {
      acc += elem.price * elem.count;
      return acc;
    }, 0);
  }
  return 0;
});
let [count, updateCount] = useState(cartItems.length);

React.useEffect(() => {
  if (cartItems) {
    updateCount(cartItems.length);
    // item object {id: "2", name: "Cucumber", category: "vegetable", price: 50, // //count: 0}
    const total = cartItems.reduce((acc, elem) => {
      acc += elem.price * elem.count;
      return acc;
    }, 0);
    updateTotal(total);
  }
}, [cartItems]);

So, basically you need to initiate the state once you get some value from the useItems and then also need to update it when cartItems reference changes


Related Query

More Query from same tag