Home > Blockchain >  What happens to React Clean Up Function After Unmount
What happens to React Clean Up Function After Unmount

Time:10-14

useEffect(() => {
    if (productId && productId !== "") fetchProductDetail(productId);
    return () => {
      dispatch(removeSelectedProduct());
    };
  }, [productId]);

In this UseEffect function will the cleanup function be in memory if the component unmounts ? If we return to the route of the component will the cleanup function run or will it be lost forever on unmounting?

CodePudding user response:

Take a look at the useEffect cleanup documentation. In your instance, () => dispatch(removeSelectedProduct()) will run every time productId changes, and when the component finally unmounts.

The needed variables/functions will remain in scope, because they are part of a closure, i.e., references to the surrounding variables that are used are bound together with the function and live as long as it lives. As long as there is a reference to something, the runtime won't garbage collect it.

  • Related