Reselect is a simple library for creating memoized, composable selector functions. Reselect selectors can be used to efficiently compute derived data from the Redux store.
In the above example, select calls selectTodos to calculate visibleTodos. This works great, but there is a drawback: visibleTodos is calculated every time the component is updated. If the state tree is large, or the calculation expensive, repeating the calculation on every update may cause performance problems. Reselect can help to avoid these unnecessary recalculations.
Creating a Memoized Selector
We would like to replace select with a memoized selector that recalculates visibleTodos when the value of state.todos or state.visibilityFilter changes, but not when changes occur in other (unrelated) parts of the state tree.
Reselect provides a function createSelector for creating memoized selectors. createSelector takes an array of input-selectors and a transform function as its arguments. If the Redux state tree is mutated in a way that causes the value of an input-selector to change, the selector will call its transform function with the values of the input-selectors as arguments and return the result. If the values of the input-selectors are the same as the previous call to the selector, it will return the previously computed value instead of calling the transform function.
Let's define a memoized selector named visibleTodosSelector to replace select:
In the example above, visibilityFilterSelector and todosSelector are input-selectors. They are created as ordinary non-memoized selector functions because they do not transform the data they select. visibleTodosSelector on the other hand is a memoized selector. It takes visibilityFilterSelector and todosSelector as input-selectors, and a transform function that calculates the filtered todos list.
Composing Selectors
A memoized selector can itself be an input-selector to another memoized selector. Here is visibleTodosSelector being used as an input-selector to a selector that further filters the todos by keyword: