Reselect

Selector library for Redux

README

Reselect


A library for creating memoized "selector" functions. Commonly used with Redux, but usable with any plain JS immutable data as well.

- Selectors can compute derived data, allowing Redux to store the minimal possible state.
- Selectors are efficient. A selector is not recomputed unless one of its arguments changes.
- Selectors are composable. They can be used as input to other selectors.

The Redux docs usage page on Deriving Data with Selectors covers the purpose and motivation for selectors, why memoized selectors are useful, typical Reselect usage patterns, and using selectors with React-Redux.
[![GitHub Workflow Status][build-badge]][build] [![npm package][npm-badge]][npm] [![Coveralls][coveralls-badge]][coveralls]

Installation


Redux Toolkit


While Reselect is not exclusive to Redux, it is already included by default in the official Redux Toolkit package - no further installation needed.

  1. ``` js
  2. import { createSelector } from '@reduxjs/toolkit'
  3. ```

Standalone


For standalone usage, install the reselect package:

  1. ``` sh
  2. npm install reselect

  3. yarn add reselect
  4. ```

Basic Usage


Reselect exports a createSelector API, which generates memoized selector functions. createSelector accepts one or more "input" selectors, which extract values from arguments, and an "output" selector that receives the extracted values and should return a derived value. If the generated selector is called multiple times, the output will only be recalculated when the extracted values have changed.

You can play around with the following example in this CodeSandbox:

  1. ``` js
  2. import { createSelector } from 'reselect'

  3. const selectShopItems = state => state.shop.items
  4. const selectTaxPercent = state => state.shop.taxPercent

  5. const selectSubtotal = createSelector(selectShopItems, items =>
  6.   items.reduce((subtotal, item) => subtotal + item.value, 0)
  7. )

  8. const selectTax = createSelector(
  9.   selectSubtotal,
  10.   selectTaxPercent,
  11.   (subtotal, taxPercent) => subtotal * (taxPercent / 100)
  12. )

  13. const selectTotal = createSelector(
  14.   selectSubtotal,
  15.   selectTax,
  16.   (subtotal, tax) => ({ total: subtotal + tax })
  17. )

  18. const exampleState = {
  19.   shop: {
  20.     taxPercent: 8,
  21.     items: [
  22.       { name: 'apple', value: 1.2 },
  23.       { name: 'orange', value: 0.95 }
  24.     ]
  25.   }
  26. }

  27. console.log(selectSubtotal(exampleState)) // 2.15
  28. console.log(selectTax(exampleState)) // 0.172
  29. console.log(selectTotal(exampleState)) // { total: 2.322 }
  30. ```

Table of Contents


- API
  - [createSelector(...inputSelectors | [inputSelectors], resultFunc, selectorOptions?)](#createselectorinputselectors--inputselectors-resultfunc-selectoroptions)
    - [Customize equalityCheck for defaultMemoize](#customize-equalitycheck-for-defaultmemoize)
- FAQ

API


createSelector(...inputSelectors | [inputSelectors], resultFunc, selectorOptions?)


Accepts one or more "input selectors" (either as separate arguments or a single array), a single "output selector" / "result function", and an optional options object, and generates a memoized selector function.

When the selector is called, each input selector will be called with all of the provided arguments. The extracted values are then passed as separate arguments to the output selector, which should calculate and return a final result. The inputs and result are cached for later use.

If the selector is called again with the same arguments, the previously cached result is returned instead of recalculating a new result.

createSelector determines if the value returned by an input-selector has changed between calls using reference equality (===). Inputs to selectors created with createSelector should be immutable.

By default, selectors created with createSelector have a cache size of 1. This means they always recalculate when the value of an input-selector changes, as a selector only stores the preceding value of each input-selector. This can be customized by passing a selectorOptions object with a memoizeOptions field containing options for the built-in defaultMemoize memoization function .

  1. ``` js
  2. const selectValue = createSelector(
  3.   state => state.values.value1,
  4.   state => state.values.value2,
  5.   (value1, value2) => value1 + value2
  6. )

  7. // You can also pass an array of selectors
  8. const selectTotal = createSelector(
  9.   [state => state.values.value1, state => state.values.value2],
  10.   (value1, value2) => value1 + value2
  11. )

  12. // Selector behavior can be customized
  13. const customizedSelector = createSelector(
  14.   state => state.a,
  15.   state => state.b,
  16.   (a, b) => a + b,
  17.   {
  18.     // New in 4.1: Pass options through to the built-in `defaultMemoize` function
  19.     memoizeOptions: {
  20.       equalityCheck: (a, b) => a === b,
  21.       maxSize: 10,
  22.       resultEqualityCheck: shallowEqual
  23.     }
  24.   }
  25. )
  26. ```

Selectors are typically called with a Redux state value as the first argument, and the input selectors extract pieces of the state object for use in calculations. However, it's also common to want to pass additional arguments, such as a value to filter by. Since input selectors are given all arguments, they can extract the additional arguments and pass them to the output selector:

  1. ``` js
  2. const selectItemsByCategory = createSelector(
  3.   [
  4.     // Usual first input - extract value from `state`
  5.     state => state.items,
  6.     // Take the second arg, `category`, and forward to the output selector
  7.     (state, category) => category
  8.   ],
  9.   // Output selector gets (`items, category)` as args
  10.   (items, category) => items.filter(item => item.category === category)
  11. )
  12. ```

defaultMemoize(func, equalityCheckOrOptions = defaultEqualityCheck)


defaultMemoize memoizes the function passed in the func parameter. It is the standard memoize function used by createSelector.

defaultMemoize has a default cache size of 1. This means it always recalculates when the value of an argument changes. However, this can be customized as needed with a specific max cache size (new in 4.1).

defaultMemoize determines if an argument has changed by calling the equalityCheck function. As defaultMemoize is designed to be used with immutable data, the default equalityCheck function checks for changes using reference equality:

  1. ``` js
  2. function defaultEqualityCheck(previousVal, currentVal) {
  3.   return currentVal === previousVal
  4. }
  5. ```

As of Reselect 4.1, defaultMemoize also accepts an options object as its first argument instead of equalityCheck. The options object may contain:

  1. ```ts
  2. interface DefaultMemoizeOptions {
  3.   equalityCheck?: EqualityFn
  4.   resultEqualityCheck?: EqualityFn
  5.   maxSize?: number
  6. }
  7. ```

Available options are:

- equalityCheck: used to compare the individual arguments of the provided calculation function
- resultEqualityCheck: if provided, used to compare a newly generated output value against previous values in the cache. If a match is found, the old value is returned. This address the common todos.map(todo => todo.id) use case, where an update to another field in the original data causes a recalculate due to changed references, but the output is still effectively the same.
- maxSize: the cache size for the selector. If maxSize is greater than 1, the selector will use an LRU cache internally

The returned memoized function will have a .clearCache() method attached.

defaultMemoize can also be used with createSelectorCreator to create a new selector factory that always has the same settings for each selector.

createSelectorCreator(memoize, ...memoizeOptions)


createSelectorCreator can be used to make a customized version of createSelector.

The memoize argument is a memoization function to replace defaultMemoize.

The ...memoizeOptions rest parameters are zero or more configuration options to be passed to memoizeFunc. The selectors resultFunc is passed as the first argument to memoize and the memoizeOptions are passed as the second argument onwards:

  1. ``` js
  2. const customSelectorCreator = createSelectorCreator(
  3.   customMemoize, // function to be used to memoize resultFunc
  4.   option1, // option1 will be passed as second argument to customMemoize
  5.   option2, // option2 will be passed as third argument to customMemoize
  6.   option3 // option3 will be passed as fourth argument to customMemoize
  7. )

  8. const customSelector = customSelectorCreator(
  9.   input1,
  10.   input2,
  11.   resultFunc // resultFunc will be passed as first argument to customMemoize
  12. )
  13. ```

Internally customSelector calls the memoize function as follows:

  1. ``` js
  2. customMemoize(resultFunc, option1, option2, option3)
  3. ```

Here are some examples of how you might use createSelectorCreator:

Customize equalityCheck for defaultMemoize


  1. ``` js
  2. import { createSelectorCreator, defaultMemoize } from 'reselect'
  3. import isEqual from 'lodash.isequal'

  4. // create a "selector creator" that uses lodash.isequal instead of ===
  5. const createDeepEqualSelector = createSelectorCreator(defaultMemoize, isEqual)

  6. // use the new "selector creator" to create a selector
  7. const selectSum = createDeepEqualSelector(
  8.   state => state.values.filter(val => val < 5),
  9.   values => values.reduce((acc, val) => acc + val, 0)
  10. )
  11. ```

Use memoize function from Lodash for an unbounded cache


  1. ``` js
  2. import { createSelectorCreator } from 'reselect'
  3. import memoize from 'lodash.memoize'

  4. let called = 0
  5. const hashFn = (...args) =>
  6.   args.reduce((acc, val) => acc + '-' + JSON.stringify(val), '')
  7. const customSelectorCreator = createSelectorCreator(memoize, hashFn)
  8. const selector = customSelectorCreator(
  9.   state => state.a,
  10.   state => state.b,
  11.   (a, b) => {
  12.     called++
  13.     return a + b
  14.   }
  15. )
  16. ```

createStructuredSelector({inputSelectors}, selectorCreator = createSelector)


createStructuredSelector is a convenience function for a common pattern that arises when using Reselect. The selector passed to a connect decorator often just takes the values of its input-selectors and maps them to keys in an object:

  1. ``` js
  2. const selectA = state => state.a
  3. const selectB = state => state.b

  4. // The result function in the following selector
  5. // is simply building an object from the input selectors
  6. const structuredSelector = createSelector(selectA, selectB, (a, b) => ({
  7.   a,
  8.   b
  9. }))
  10. ```

createStructuredSelector takes an object whose properties are input-selectors and returns a structured selector. The structured selector returns an object with the same keys as the inputSelectors argument, but with the selectors replaced with their values.

  1. ``` js
  2. const selectA = state => state.a
  3. const selectB = state => state.b

  4. const structuredSelector = createStructuredSelector({
  5.   x: selectA,
  6.   y: selectB
  7. })

  8. const result = structuredSelector({ a: 1, b: 2 }) // will produce { x: 1, y: 2 }
  9. ```

Structured selectors can be nested:

  1. ``` js
  2. const nestedSelector = createStructuredSelector({
  3.   subA: createStructuredSelector({
  4.     selectorA,
  5.     selectorB
  6.   }),
  7.   subB: createStructuredSelector({
  8.     selectorC,
  9.     selectorD
  10.   })
  11. })
  12. ```

FAQ


Q: Why isn’t my selector recomputing when the input state changes?


A: Check that your memoization function is compatible with your state update function (i.e. the reducer if you are using Redux). For example, a selector created with createSelector will not work with a state update function that mutates an existing object instead of creating a new one each time. createSelector uses an identity check (===) to detect that an input has changed, so mutating an existing object will not trigger the selector to recompute because mutating an object does not change its identity. Note that if you are using Redux, mutating the state object is almost certainly a mistake.

The following example defines a simple selector that determines if the first todo item in an array of todos has been completed:

  1. ``` js
  2. const selectIsFirstTodoComplete = createSelector(
  3.   state => state.todos[0],
  4.   todo => todo && todo.completed
  5. )
  6. ```

The following state update function will not work with selectIsFirstTodoComplete:

  1. ``` js
  2. export default function todos(state = initialState, action) {
  3.   switch (action.type) {
  4.     case COMPLETE_ALL:
  5.       const areAllMarked = state.every(todo => todo.completed)
  6.       // BAD: mutating an existing object
  7.       return state.map(todo => {
  8.         todo.completed = !areAllMarked
  9.         return todo
  10.       })

  11.     default:
  12.       return state
  13.   }
  14. }
  15. ```

The following state update function will work with selectIsFirstTodoComplete:

  1. ``` js
  2. export default function todos(state = initialState, action) {
  3.   switch (action.type) {
  4.     case COMPLETE_ALL:
  5.       const areAllMarked = state.every(todo => todo.completed)
  6.       // GOOD: returning a new object each time with Object.assign
  7.       return state.map(todo =>
  8.         Object.assign({}, todo, {
  9.           completed: !areAllMarked
  10.         })
  11.       )

  12.     default:
  13.       return state
  14.   }
  15. }
  16. ```

If you are not using Redux and have a requirement to work with mutable data, you can use createSelectorCreator to replace the default memoization function and/or use a different equality check function. See here and here for examples.

Q: Why is my selector recomputing when the input state stays the same?


A: Check that your memoization function is compatible with your state update function (i.e. the reducer if you are using Redux). For example, a selector created with createSelector that recomputes unexpectedly may be receiving a new object on each update whether the values it contains have changed or not. createSelector uses an identity check (===) to detect that an input has changed, so returning a new object on each update means that the selector will recompute on each update.

  1. ``` js
  2. import { REMOVE_OLD } from '../constants/ActionTypes'

  3. const initialState = [
  4.   {
  5.     text: 'Use Redux',
  6.     completed: false,
  7.     id: 0,
  8.     timestamp: Date.now()
  9.   }
  10. ]

  11. export default function todos(state = initialState, action) {
  12.   switch (action.type) {
  13.     case REMOVE_OLD:
  14.       return state.filter(todo => {
  15.         return todo.timestamp + 30 * 24 * 60 * 60 * 1000 > Date.now()
  16.       })
  17.     default:
  18.       return state
  19.   }
  20. }
  21. ```

The following selector is going to recompute every time REMOVE_OLD is invoked because Array.filter always returns a new object. However, in the majority of cases the REMOVE_OLD action will not change the list of todos so the recomputation is unnecessary.

  1. ``` js
  2. import { createSelector } from 'reselect'

  3. const todosSelector = state => state.todos

  4. export const selectVisibleTodos = createSelector(
  5.   todosSelector,
  6.   (todos) => {
  7.     ...
  8.   }
  9. )
  10. ```

You can eliminate unnecessary recomputations by returning a new object from the state update function only when a deep equality check has found that the list of todos has actually changed:

  1. ``` js
  2. import { REMOVE_OLD } from '../constants/ActionTypes'
  3. import isEqual from 'lodash.isequal'

  4. const initialState = [
  5.   {
  6.     text: 'Use Redux',
  7.     completed: false,
  8.     id: 0,
  9.     timestamp: Date.now()
  10.   }
  11. ]

  12. export default function todos(state = initialState, action) {
  13.   switch (action.type) {
  14.     case REMOVE_OLD:
  15.       const updatedState = state.filter(todo => {
  16.         return todo.timestamp + 30 * 24 * 60 * 60 * 1000 > Date.now()
  17.       })
  18.       return isEqual(updatedState, state) ? state : updatedState
  19.     default:
  20.       return state
  21.   }
  22. }
  23. ```

Alternatively, the default equalityCheck function in the selector can be replaced by a deep equality check:

  1. ``` js
  2. import { createSelectorCreator, defaultMemoize } from 'reselect'
  3. import isEqual from 'lodash.isequal'

  4. const selectTodos = state => state.todos

  5. // create a "selector creator" that uses lodash.isequal instead of ===
  6. const createDeepEqualSelector = createSelectorCreator(
  7.   defaultMemoize,
  8.   isEqual
  9. )

  10. // use the new "selector creator" to create a selector
  11. const mySelector = createDeepEqualSelector(
  12.   todosSelector,
  13.   (todos) => {
  14.     ...
  15.   }
  16. )
  17. ```

Always check that the cost of an alternative equalityCheck function or deep equality check in the state update function is not greater than the cost of recomputing every time. If recomputing every time does work out to be the cheaper option, it may be that for this case Reselect is not giving you any benefit over passing a plain mapStateToProps function to connect.

Q: Can I use Reselect without Redux?


A: Yes. Reselect has no dependencies on any other package, so although it was designed to be used with Redux it can be used independently. It can be used with any plain JS data, such as typical React state values, as long as that data is being updated immutably.

Q: How do I create a selector that takes an argument?


As shown in the API reference section above, provide input selectors that extract the arguments and forward them to the output selector for calculation:

  1. ``` js
  2. const selectItemsByCategory = createSelector(
  3.   [
  4.     // Usual first input - extract value from `state`
  5.     state => state.items,
  6.     // Take the second arg, `category`, and forward to the output selector
  7.     (state, category) => category
  8.   ],
  9.   // Output selector gets (`items, category)` as args
  10.   (items, category) => items.filter(item => item.category === category)
  11. )
  12. ```

Q: The default memoization function is no good, can I use a different one?


A: We think it works great for a lot of use cases, but sure. See these examples.

Q: How do I test a selector?


A: For a given input, a selector should always produce the same output. For this reason they are simple to unit test.

  1. ``` js
  2. const selector = createSelector(
  3.   state => state.a,
  4.   state => state.b,
  5.   (a, b) => ({
  6.     c: a * 2,
  7.     d: b * 3
  8.   })
  9. )

  10. test('selector unit test', () => {
  11.   assert.deepEqual(selector({ a: 1, b: 2 }), { c: 2, d: 6 })
  12.   assert.deepEqual(selector({ a: 2, b: 3 }), { c: 4, d: 9 })
  13. })
  14. ```

It may also be useful to check that the memoization function for a selector works correctly with the state update function (i.e. the reducer if you are using Redux). Each selector has a recomputations method that will return the number of times it has been recomputed:

  1. ``` js
  2. suite('selector', () => {
  3.   let state = { a: 1, b: 2 }

  4.   const reducer = (state, action) => ({
  5.     a: action(state.a),
  6.     b: action(state.b)
  7.   })

  8.   const selector = createSelector(
  9.     state => state.a,
  10.     state => state.b,
  11.     (a, b) => ({
  12.       c: a * 2,
  13.       d: b * 3
  14.     })
  15.   )

  16.   const plusOne = x => x + 1
  17.   const id = x => x

  18.   test('selector unit test', () => {
  19.     state = reducer(state, plusOne)
  20.     assert.deepEqual(selector(state), { c: 4, d: 9 })
  21.     state = reducer(state, id)
  22.     assert.deepEqual(selector(state), { c: 4, d: 9 })
  23.     assert.equal(selector.recomputations(), 1)
  24.     state = reducer(state, plusOne)
  25.     assert.deepEqual(selector(state), { c: 6, d: 12 })
  26.     assert.equal(selector.recomputations(), 2)
  27.   })
  28. })
  29. ```

Additionally, selectors keep a reference to the last result function as .resultFunc. If you have selectors composed of many other selectors this can help you test each selector without coupling all of your tests to the shape of your state.

For example if you have a set of selectors like this:

selectors.js

  1. ``` js
  2. export const selectFirst = createSelector( ... )
  3. export const selectSecond = createSelector( ... )
  4. export const selectThird = createSelector( ... )

  5. export const myComposedSelector = createSelector(
  6.   selectFirst,
  7.   selectSecond,
  8.   selectThird,
  9.   (first, second, third) => first * second < third
  10. )
  11. ```

And then a set of unit tests like this:

test/selectors.js

  1. ``` js
  2. // tests for the first three selectors...
  3. test("selectFirst unit test", () => { ... })
  4. test("selectSecond unit test", () => { ... })
  5. test("selectThird unit test", () => { ... })

  6. // We have already tested the previous
  7. // three selector outputs so we can just call `.resultFunc`
  8. // with the values we want to test directly:
  9. test("myComposedSelector unit test", () => {
  10.   // here instead of calling selector()
  11.   // we just call selector.resultFunc()
  12.   assert(myComposedSelector.resultFunc(1, 2, 3), true)
  13.   assert(myComposedSelector.resultFunc(2, 2, 1), false)
  14. })
  15. ```

Finally, each selector has a resetRecomputations method that sets
recomputations back to 0. The intended use is for a complex selector that may
have many independent tests and you don't want to manually manage the
computation count or create a "dummy" selector for each test.

Q: Can I share a selector across multiple component instances?


A: Yes, although it requires some planning.

As of Reselect 4.1, you can create a selector with a cache size greater than one by passing in a maxSize option under memoizeOptions for use with the built-in defaultMemoize.

Otherwise, selectors created using createSelector only have a cache size of one. This can make them unsuitable for sharing across multiple instances if the arguments to the selector are different for each instance of the component. There are a couple of ways to get around this:

- Create a factory function which returns a new selector for each instance of the component. This can be called in a React component inside the useMemo hook to generate a unique selector instance per component.
- Create a custom selector with a cache size greater than one using createSelectorCreator

Q: Are there TypeScript Typings?


A: Yes! Reselect is now written in TS itself, so they should Just Work™.

Q: I am seeing a TypeScript error: Type instantiation is excessively deep and possibly infinite


A: This can often occur with deeply recursive types, which occur in this library. Please see [this
comment](https://github.com/reduxjs/reselect/issues/534#issuecomment-956708953) for a discussion of the problem, as
relating to nested selectors.

Q: How can I make a curried selector?


A: Try these helper functions courtesy of MattSPalmer

Related Projects



Enhances Reselect selectors by wrapping createSelector and returning a memoized collection of selectors indexed with the cache key returned by a custom resolver function.

Useful to reduce selectors recalculation when the same selector is repeatedly called with one/few different arguments.


Chrome extension and companion lib for debugging selectors.

- Measure selector recomputations across the app and identify performance bottlenecks
- Check selector dependencies, inputs, outputs, and recomputations at any time with the chrome extension
- Statically export a JSON representation of your selector graph for further analysis


Flipper plugin and and the connect app for debugging selectors inReact Native Apps.

Inspired by Reselect Tools, so it also has all functionality from this library and more, but only for React Native and Flipper.

- Selectors Recomputations count in live time across the App for identify performance bottlenecks
- Highlight most recomputed selectors
- Dependency Graph
- Search by Selectors Graph
- Selectors Inputs
- Selectors Output (In case if selector not dependent from external arguments)
- Shows "Not Memoized (NM)" selectors

License


MIT

Prior Art and Inspiration


Originally inspired by getters in NuclearJS, subscriptions in re-frame and this proposal from speedskater.

[build-badge]: https://img.shields.io/github/workflow/status/reduxjs/redux-thunk/Tests
[build]: https://github.com/reduxjs/reselect/actions/workflows/build-and-test-types.yml
[npm-badge]: https://img.shields.io/npm/v/reselect.svg?style=flat-square
[npm]: https://www.npmjs.org/package/reselect
[coveralls-badge]: https://img.shields.io/coveralls/reduxjs/reselect/master.svg?style=flat-square
[coveralls]: https://coveralls.io/github/reduxjs/reselect