2

In a tutorial I follow, they have this piece of code that creates 2 selectors:

const selectCart = (state) => state.cart;

export const selectCartHidden = createSelector(
  [selectCart],
  (cart) => cart.hidden
);
...
export const selectCartItemsCount = createSelector(
  [selectCartItems],
  (cartItems) => cartItems.reduce((a, item) => a + item.quantity, 0)
);

According to reselect, you should use createSelector if you are computing a value from state, so the second selector makes sense to me, but how about the first one? It is simply extracting data without any calculation, so would it be better to just write: selectCartHidden = state => state.cart.hidden, because it will return the same value if unrelated part of the state changes anyway, so there is no need to memoize it?

Free Me
  • 195
  • 2
  • 10

2 Answers2

1

If you make a selector like this: state=>state.cart.hidden you have one function answering 2 questions:

  1. How to get a cart
  2. Is cart hidden

If you use state.cart in multiple selectors to get the cart and you refactor your state so getting the cart changes to something else then you have to change all the selectors but if you re use the logic of getting the cart you only need to change the selectCart function.

This is the powerful design benefit you get from using reselect called composition

HMR
  • 37,593
  • 24
  • 91
  • 160
0

You are right, the first selector is unnecessary.

phry
  • 35,762
  • 5
  • 67
  • 81