Prevent useEffect() from executing unnecessarily

If a component includes the React useEffect() hook, it runs immediately after the component is rendered, and then each time any of its declared dependencies change. To avoid executing useEffect() unnecessarily, you should construct your code so that useEffect() runs only when it is actually needed.

In the following example, useEffect() is invoked after the component is first rendered, but the conditional statement ensures that the method’s logic is executed only if any of the variant options change. The logic is skipped if no option is selected:

useEffect(() => {
  // Fire action only if variantOptions exist and an option is changed
    if (variantOptions && optionChanged) {
      // Get the latest selected item from the options
      const currentSelectedItem = getCurrentSelectedItem(variantOptions);
      const variantOptionsLite = {};
      // Remaining code
    }
}, [variantOptions,variantOptionPermutations, optionChanged, widgetId, action,variantToSkuLookup]);