Cleaning up state on useEffect hook

228 Views Asked by At

Can someone give me a light on what may be happening here? I have an effect that basically, when I load a product page it updates an state with an array of items, but when I change the product (a prop) it's not cleaning up my state. The code is below, can someone see what may be missing?

const [cartItems, setCartItems] = useState<any>([]);
useEffect(() => {
    if (product) {
      handleCartArray(product.name, variant.sku, variant.price, product.productId);
    }
    return () => {
      console.log('is this running?');

      cleanCartItems();
    };
  }, [product]);

  function cleanCartItems() {
    console.log('I am trying to clean the cart items');
    setCartItems([]);
  }

Not really much to be added here. I am trying to clean up this state everytime a new product is loaded, but it isn't working.

2

There are 2 best solutions below

0
Suryasish Paul On

useEffect dependencies only fire up the code within when the state of one/all of the dependencies changes. In your case product seems like a simple variable. Define product using useState or some centralised state management system and your useEffect will work perfectly. Good luck!

4
Sina Haghshenas On

Make sure that your useEffect hook is running (you haven't explained what product is, so I'm not even sure it's running). Also how about calling setCartItems([]) inside the the return statement in useEffect itself? The arrow statement is a function itself, right now it's literally a function only being used to callback another function.