Reselect is a Selector library for Redux
Iren Korkishko Aug 7
Originally I shared this post to Syndicode blog.
A 'store' is one of the Redux core concepts, and when you use Redux it's vital to understand how to structure the data in this store. To simplify your task, I'm reminding you about Reselect, a popular library that provides a convenient way of getting values from a store in a React-Redux application. To clarify, Reselect is a Selector library for Redux, with memoization ability.
In Redux a selector is a piece of logic that gets a specific piece of state from the store. Also, a selector can compute data from a given state, allowing the store to keep only basic raw data.
When you use the createSelector() function, it memoizes an output of every input selector and recalculates the resulting value only if any of the input selectors changes its output.
Reselect is a memoized selector function, composed of selectors, that returns something you want in your component’s props.
If you create selectors with Reselect, you'll get a few benefits in terms of developer experience and performance:
- Selectors created using Reselect’s
createSelectorfunction are memoized. The function remembers the arguments passed-in the last time it was invoked and doesn’t recalculate if the arguments are the same. A selector is not recomputed unless one of its arguments changes.
- Reselect selectors can be easily composed/chained together. They can be even used as input to other selectors. Each selector stays small and focused on one task.
- Selectors can compute derived data, allowing Redux to store the minimal possible state.
- Motivation for Memoized Selectors
- Creating a Memoized Selector
- Composing Selectors
- Connecting a Selector to the Redux Store
- Accessing React Props in Selectors
- Sharing Selectors with Props Across Multiple Component Instances
A few tips for using Reselect library:
- Use createSelector() from Reselect to create a selector, if it transforms value from the state in any way.
- Avoid curried selectors. You can pass all the arguments you need using the second argument of a selector.
- Be careful with dispatching actions to the store from lifecycle functions. In general, avoid doing this. If you face with it, try to compare props manually before dispatching an action.
Read more about Reselect on the project's open source page.