How can I dispatch function in redux?

My recommendation would be to not store redundant (derived) information in state. This means you don’t need to (nor should you!) store the total in the state. The main reason this is a problem is that it gives your state an opportunity to contradict itself… if your state’s total key doesn’t equal the sum of the item totals, you’ve got a big problem!

Instead, you can create a function that calculates the total and simply call that when you need it. For example:

const calculateTotal = state => {
  let total = state.cart.reduce((total, item) => {
    return total + item.quantity * item.product.price 
  }, 0);
  // Assuming you just have one coupon, you could maintain a boolean in state
  if (state.hasCoupon) {
    total -= 50;
  }
  return total;
}

And then, anywhere in your code you need to get the total, you can simple use this function. It’s not uncommon to include this sort of function in mapStateToProps:

const mapStateToProps = state => ({
  total: calculateTotal(state);
});

If you end up with a lot of derived state, you may see some advantages from using a selector library like Reselect which can help you build selectors derived from other selectors and implements memoization for performance boosts.

Leave a Comment