Why selectors?

Redux provides all state transformations and how these transformations mutate the store. However, it doesn't discuss a prescribed way for components to query the store. This is where the selector comes in. As mentioned, the Redux store stores a global store for an entire application to reduce the complexity and we need a mechanism for querying this store. The use of selectors is one of the possible solutions to this problem. 

We can access the store through direct references, as follows:

const subsetOfState = store.someStateRoot.someProperty[key]

There are two issues with this approach, as follows:

  1. The application must know the actual shape of the store and whether the shape of the store is changing, and then the developer must update every single bit of application code that reads the state. 
  2. We connect React components to store using Redux to pass store as props. We can do this by using the a mapStateToProps function, which is called on every state change. The function yields recalculated props, which are compared to old props. If they differ, the components get re-rendered. This comparison is done using reference equality (===) and, if not handled properly, this can cause your components to be re-rendered unnecessarily. One way to solve this issue is by using memoized reselect. With the term, memoized, we refer to the fact that selectors calls are stored in case they might need to be retrieved again. Memoization is one of the programming practices of getting long recursive/iterative functions to execute faster. 

Moreover, the documentation page of reselect (https://github.com/reduxjs/reselect) provides three great reasons as to why we should use it, as follows:

  1. Selectors can compute derived data. This allows the Redux store to use a minimal store state. 
  2. Selectors are efficient. This is due to the fact that re-computation is not done unless some argument changes. 
  3. Selectors are composable. We've already learned about the concept of composing in Chapter 1, Understanding Redux

If you recall, the connect function from Chapter 1, Understanding Redux, takes two arguments mapStateToProps and mapDispatchToProps. The mapStateToProps function is a selector function, which should normally return a plain object. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset