Why does my onClick event fire every time the React component renders?

41 Views Asked by At

I have a React function component for a producxt page. I am counting the number of products a user wishes to add to their basket using

const [productAmount, setProductAmount] = useState(1);

Every time a user clicks on the product counter, it updates the value of the productAmount:

  // Update counter
 const incrementAmount = () => {
    setProductAmount(productAmount+1)
  }

  const decrementAmount = () => {
    if (productAmount == 1){
      setProductAmount(1);
    }
    else {
      setProductAmount(productAmount-1);
    }
  }

Users trigger this update using:

<div className='pci' onClick={decrementAmount}>-</div>
<div className='pci' onClick={incrementAmount}>+</div>

This all works fine.

When user wants to add these products to the basket, I want to write this number to localstorage using:

  //Update cart
  const updateCart = () => {
    // Write number of products in cart to local storage
    localStorage.setItem("cartnumber", productAmount);
  }

Users trigger this update using:

<div className='productaddtocart' onClick={updateCart({productAmount})}>Add to cart</div>

My problem is that the localstorage is updated, I assume via the updateCart function, every time I click on

<div className='pci' onClick={decrementAmount}>-</div>
<div className='pci' onClick={incrementAmount}>+</div>

Why is this happening and how do I get the localstorage to update ony after a user clicks on the "Add to Cart" CTA?

See above for details

1

There are 1 best solutions below

0
Anthony Bertrand On

Because you're calling your function immediately. Try encapsulating it like so :

<div className='productaddtocart' onClick={() => updateCart({productAmount})}>Add to cart</div>