Why Reselect is widely used in React-Redux applications

Tram Ho

1. What is a selector?

Before we can understand what reselect works, we must first understand what a selector is. selector can be understood as a logical segment used to calculate a certain value from available values, or simply to take a value from an existing value.

In a React application that uses Redux, we can write our own selector to get or calculate a value from the values ​​in the redux store to reuse them in the mapStateToProps function. For example:

However, whenever users are update , getUserViaId and getUser will have to recalculate. This is the problem of simple selector , when users become bigger, or the calculations inside getUserViaId more complicated, consume more resources and as a result our app will be … slower. ??? . This is where the Reselect library shines. ???

2. How does the reselector library work?

The reselector is simply a library that helps us solve the above problem by comparing the parameters of a selector (created by the reselect library) with each other, that selector will only perform calculations if the parameters The old is khác from the new parameter.

reselector is just a javascript library so you can use it with any javascript framework or library, not just react.

3. How to use the reselector library

The README file in the repo of github reselector library is really quality, easy to read, clear and very easy to understand, so I’ll just show you how to use the basic of this letter.

OKay, To create a Selector using the reselector library, we will have to:

  1. Create a … selector ? , this selector gets into a store of redux and returns a value, what is this value for? Please read the steps below and see VD to understand better.
  2. createSelector selector into the createSelector method of the reselector to create a new selector . This method takes a selector or an array of selector and finally a callback function, this callback function takes the parameter that the selector we pass into createSelector and operates as we wrote in item 2 . For example:

1. File to create selector:

2. Use the selector:

As I mentioned in step 2 , the first parameter of createSelector can also be an array of selector .

One more thing, as I mentioned, reselect is just a javascript library so you can use it with frameworks or pure javascript libraries or javascript too!

4. Conclusion

Above are some things that I would like to introduce to you about the reselect library. I hope that through this article, you just learn about react and redux will know more about reselect and the reason behind the popularity of this library.

Share the news now

Source : Viblo