{"name":"reselect","version":"4.1.0-beta.2","keywords":["react","redux"],"license":"MIT","_id":"reselect@4.1.0-beta.2","maintainers":[{"name":"gaearon","email":"dan.abramov@gmail.com"},{"name":"timdorr","email":"timdorr@timdorr.com"},{"name":"threehams","email":"threehams@gmail.com"},{"name":"faassen","email":"faassen@startifact.com"},{"name":"ellbee","email":"l_bannard@yahoo.co.uk"},{"name":"alex3165","email":"alexr.3165@gmail.com"},{"name":"acemarke","email":"mark.erikson@gmail.com"}],"contributors":[{"url":"https://github.com/ellbee","name":"Lee Bannard","email":"l_bannard@yahoo.co.uk"},{"url":"https://github.com/faassen","name":"Martijn Faassen"},{"url":"https://github.com/ianks","name":"Ian Ker-Seymer","email":"i.kerseymer@gmail.com"},{"url":"https://github.com/SpainTrain","name":"Mike S"},{"url":"https://github.com/omnidan","name":"Daniel Bugl","email":"me@omnidan.net"},{"url":"https://github.com/ryanatkn","name":"Ryan"},{"url":"https://github.com/HeyImAlex","name":"Alex Guerra","email":"alex@heyimalex.com"},{"url":"https://github.com/speedskater","name":"speedskater"},{"url":"https://github.com/sericaia","name":"Daniela Borges"},{"url":"https://github.com/existentialism","name":"Brian Ng","email":"bng412@gmail.com"},{"url":"https://github.com/chentsulin","name":"C. T. Lin","email":"chentsulin@gmail.com"},{"url":"https://github.com/chungchiehlun","name":"Jay","email":"wuceh14678@gmail.com"},{"url":"https://github.com/madebyherzblut","name":"Christian Schuhmann"},{"url":"https://github.com/volrath","name":"Daniel Barreto","email":"daniel.barreto.n@gmail.com"},{"url":"https://github.com/ifunk","name":"Adam Royle"},{"url":"https://github.com/elliotcm","name":"Elliot Crosby-McCullough","email":"elliot.cm@gmail.com"},{"url":"https://github.com/frankwallis","name":"frankwallis"},{"url":"https://github.com/kaddopur","name":"Jason Huang","email":"chaoju.huang@gmail.com"},{"url":"https://github.com/joshkel","name":"Josh Kelley"},{"url":"https://github.com/leonaves","name":"Leon Aves"},{"url":"https://github.com/markdalgleish","name":"Mark Dalgleish"},{"url":"https://github.com/chromakode","name":"Max Goodman","email":"c@chromako.de"},{"url":"https://github.com/weblancaster","name":"Michael Lancaster","email":"michaell.llancaster@gmail.com"},{"url":"https://github.com/zalmoxisus","name":"Mihail Diordiev"},{"url":"https://github.com/PSpSynedra","name":"PSpSynedra"},{"url":"https://github.com/SimenB","name":"Simen Bekkhus","email":"sbekkhus91@gmail.com"},{"url":"https://github.com/WadePeterson","name":"Wade Peterson"},{"url":"https://github.com/ambar","name":"长天之云","email":"ambar.lee@gmail.com"},{"url":"https://github.com/courthead","name":"Courtland Allen","email":"csallen@alum.mit.edu"},{"url":"https://github.com/HenrikJoreteg","name":"Henrik Joreteg","email":"henrik@joreteg.com"},{"url":"https://github.com/kyldvs","name":"Kyle Davis"},{"url":"https://github.com/clickclickonsal","name":"Salvador Hernandez","email":"s.hernandez5400@gmail.com"},{"url":"https://github.com/npbee","name":"Nick Ball"},{"url":"https://github.com/mctep","name":"mctep"},{"url":"https://github.com/jacobrask","name":"Jacob Rask","email":"jacob@jacobrask.net"},{"url":"https://github.com/luqmaan","name":"Luqmaan Dawoodjee","email":"ldawoodjee@gmail.com"},{"url":"https://github.com/wbreakell","name":"Walter Breakell"},{"url":"https://github.com/matthetherington","name":"Matthew Hetherington"},{"url":"https://github.com/mjw56","name":"Mike Wilcox","email":"mwilcox56@gmail.com"},{"url":"https://github.com/threehams","name":"David Edmondson"},{"url":"https://github.com/zandroid","name":"Andrey Zaytsev","email":"za@zalab.net"},{"url":"https://github.com/1ven","name":"1ven"},{"url":"https://github.com/alexesdev","name":"Alexey Yurchenko","email":"alexes.dev@gmail.com"},{"url":"https://github.com/dpwrussell","name":"Douglas Russell"},{"url":"https://github.com/yoni-tock","name":"Yonatan Kogan"},{"url":"https://github.com/pesho","name":"Peter Petrov"},{"url":"https://github.com/wbreakell","name":"Walter Breakell"},{"url":"https://github.com/madeinfree","name":"Whien","email":"sal95610@gmail.com"},{"url":"https://github.com/bsideup","name":"Sergei Egorov","email":"bsideup@gmail.com"},{"url":"https://github.com/jimbolla","name":"Jim Bolla"},{"url":"https://github.com/carlbernrdo","name":"Carl Bernardo"},{"url":"https://github.com/aikoven","name":"Daniel Lytkin","email":"dan.lytkin@gmail.com"},{"url":"https://github.com/johnhaley81","name":"John Haley","email":"john@haley.io"},{"url":"https://github.com/alex3165","name":"Alexandre","email":"alexr.3165@gmail.com"}],"homepage":"https://github.com/reduxjs/reselect#readme","bugs":{"url":"https://github.com/reduxjs/reselect/issues"},"dist":{"shasum":"cfeed82250c8dd19e24cbcccc0cf0fe65d885dcc","tarball":"http://registry-npm.ywwl.com/reselect/download/reselect-4.1.0-beta.2.tgz","fileCount":17,"integrity":"sha512-EHxFXNjVW+M/a64APnJmox1m2R4ywkFJ0GT/LqaVwSCUhk74z61xHn8dT/lquybX5qhbVzkRN0jSO4HS23L/kg==","signatures":[{"sig":"MEQCIEL3WNuGIwtFKgl71kfeJVY2KutbSdZRUrBp8eIIbs4EAiBZPqz3DiKgODMjOMe77P5XJV1z0vX7YkGc8vXf7Cvd8w==","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":156208,"size":25418,"noattachment":false,"key":"/reselect/-/reselect-4.1.0-beta.2.tgz"},"main":"./lib/index.js","types":"./es/index.d.ts","unpkg":"./dist/reselect.js","module":"./es/index.js","readme":"# Reselect\r\n\r\n[![GitHub Workflow Status][build-badge]][build]\r\n[![npm package][npm-badge]][npm]\r\n[![Coveralls][coveralls-badge]][coveralls]\r\n\r\nA library for creating memoized \"selector\" functions. Commonly used with Redux, but usable with any plain JS immutable data as well.\r\n\r\n- Selectors can compute derived data, allowing Redux to store the minimal possible state.\r\n- Selectors are efficient. A selector is not recomputed unless one of its arguments changes.\r\n- Selectors are composable. They can be used as input to other selectors.\r\n\r\nOriginally inspired by getters in [NuclearJS](https://github.com/optimizely/nuclear-js.git), [subscriptions](https://github.com/Day8/re-frame#just-a-read-only-cursor) in [re-frame](https://github.com/Day8/re-frame) and this [proposal](https://github.com/reduxjs/redux/pull/169) from [speedskater](https://github.com/speedskater).\r\n\r\nYou can play around with the following **example** in [this codepen](https://codepen.io/Domiii/pen/LzGNWj?editors=0010):\r\n\r\n```js\r\nimport { createSelector } from 'reselect'\r\n\r\nconst selectShopItems = state => state.shop.items\r\nconst selectTaxPercent = state => state.shop.taxPercent\r\n\r\nconst selectSubtotal = createSelector(selectShopItems, items =>\r\n  items.reduce((subtotal, item) => subtotal + item.value, 0)\r\n)\r\n\r\nconst selectTax = createSelector(\r\n  selectSubtotal,\r\n  selectTaxPercent,\r\n  (subtotal, taxPercent) => subtotal * (taxPercent / 100)\r\n)\r\n\r\nconst selectTotal = createSelector(\r\n  selectSubtotal,\r\n  taxSelector,\r\n  (subtotal, tax) => ({ total: subtotal + tax })\r\n)\r\n\r\nconst exampleState = {\r\n  shop: {\r\n    taxPercent: 8,\r\n    items: [\r\n      { name: 'apple', value: 1.2 },\r\n      { name: 'orange', value: 0.95 }\r\n    ]\r\n  }\r\n}\r\n\r\nconsole.log(selectSubtotal(exampleState)) // 2.15\r\nconsole.log(selectTax(exampleState)) // 0.172\r\nconsole.log(selectTotal(exampleState)) // { total: 2.322 }\r\n```\r\n\r\n## Table of Contents\r\n\r\n- [Reselect](#reselect)\r\n\r\n  - [Table of Contents](#table-of-contents)\r\n  - [Installation](#installation)\r\n  - [Usage Guide](#usage-guide)\r\n  - [API](#api)\r\n    - [createSelector(...inputSelectors | [inputSelectors], resultFunc, selectorOptions?)](#createselectorinputselectors--inputselectors-resultfunc-selectoroptions)\r\n    - [defaultMemoize(func, equalityCheck = defaultEqualityCheck)](#defaultmemoizefunc-equalitycheck--defaultequalitycheck)\r\n    - [createSelectorCreator(memoize, ...memoizeOptions)](#createselectorcreatormemoize-memoizeoptions)\r\n      - [Customize `equalityCheck` for `defaultMemoize`](#customize-equalitycheck-for-defaultmemoize)\r\n      - [Use memoize function from lodash for an unbounded cache](#use-memoize-function-from-lodash-for-an-unbounded-cache)\r\n    - [createStructuredSelector({inputSelectors}, selectorCreator = createSelector)](#createstructuredselectorinputselectors-selectorcreator--createselector)\r\n  - [FAQ](#faq)\r\n    - [Q: Why isn’t my selector recomputing when the input state changes?](#q-why-isnt-my-selector-recomputing-when-the-input-state-changes)\r\n    - [Q: Why is my selector recomputing when the input state stays the same?](#q-why-is-my-selector-recomputing-when-the-input-state-stays-the-same)\r\n    - [Q: Can I use Reselect without Redux?](#q-can-i-use-reselect-without-redux)\r\n    - [Q: How do I create a selector that takes an argument?](#q-how-do-i-create-a-selector-that-takes-an-argument)\r\n    - [Q: The default memoization function is no good, can I use a different one?](#q-the-default-memoization-function-is-no-good-can-i-use-a-different-one)\r\n    - [Q: How do I test a selector?](#q-how-do-i-test-a-selector)\r\n    - [Q: How do I use Reselect with Immutable.js?](#q-how-do-i-use-reselect-with-immutablejs)\r\n    - [Q: Can I share a selector across multiple component instances?](#q-can-i-share-a-selector-across-multiple-component-instances)\r\n    - [Q: Are there TypeScript Typings?](#q-are-there-typescript-typings)\r\n    - [Q: How can I make a curried selector?](#q-how-can-i-make-a-curried-selector)\r\n  - [Related Projects](#related-projects)\r\n    - [re-reselect](#re-reselect)\r\n    - [reselect-tools](#reselect-tools)\r\n    - [reselect-debugger](#reselect-debugger)\r\n    - [reselect-map](#reselect-map)\r\n  - [License](#license)\r\n\r\n  - [Why isn't my selector recomputing when the input state changes?](#q-why-isnt-my-selector-recomputing-when-the-input-state-changes)\r\n  - [Why is my selector recomputing when the input state stays the same?](#q-why-is-my-selector-recomputing-when-the-input-state-stays-the-same)\r\n  - [Can I use Reselect without Redux?](#q-can-i-use-reselect-without-redux)\r\n  - [The default memoization function is no good, can I use a different one?](#q-the-default-memoization-function-is-no-good-can-i-use-a-different-one)\r\n  - [How do I test a selector?](#q-how-do-i-test-a-selector)\r\n  - [How do I create a selector that takes an argument? ](#q-how-do-i-create-a-selector-that-takes-an-argument)\r\n  - [How do I use Reselect with Immutable.js?](#q-how-do-i-use-reselect-with-immutablejs)\r\n  - [Can I share a selector across multiple component instances?](#q-can-i-share-a-selector-across-multiple-component-instances)\r\n  - [Are there TypeScript typings?](#q-are-there-typescript-typings)\r\n  - [How can I make a curried selector?](#q-how-can-i-make-a-curried-selector)\r\n\r\n- [Related Projects](#related-projects)\r\n- [License](#license)\r\n\r\n## Installation\r\n\r\n```bash\r\nnpm install reselect\r\n\r\nyarn add reselect\r\n```\r\n\r\n## Usage Guide\r\n\r\nThe **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.\r\n\r\n## API\r\n\r\n### createSelector(...inputSelectors | [inputSelectors], resultFunc, selectorOptions?)\r\n\r\nTakes one or more selectors, or an array of selectors, computes their values and passes them as arguments to `resultFunc`.\r\n\r\n`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.\r\n\r\nBy 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 .\r\n\r\n```js\r\nconst selectValue = createSelector(\r\n  state => state.values.value1,\r\n  state => state.values.value2,\r\n  (value1, value2) => value1 + value2\r\n)\r\n\r\n// You can also pass an array of selectors\r\nconst selectTotal = createSelector(\r\n  [state => state.values.value1, state => state.values.value2],\r\n  (value1, value2) => value1 + value2\r\n)\r\n\r\n// Selector behavior can be customized\r\nconst customizedSelector = createSelector(\r\n  state => state.a,\r\n  state => state.b,\r\n  (a, b) => a + b,\r\n  {\r\n    // Pass options through to the built-in `defaultMemoize` function\r\n    memoizeOptions: {\r\n      equalityCheck: (a, b) => a === b,\r\n      maxSize: 10,\r\n      resultEqualityCheck: shallowEqual\r\n    }\r\n  }\r\n)\r\n```\r\n\r\nIt can be useful to access the props of a component from within a selector. When a selector is connected to a component with `connect`, the component props are passed as the second argument to the selector:\r\n\r\n```js\r\nconst selectAB = (state, props) => state.a * props.b\r\n\r\n// props only (ignoring state argument)\r\nconst selectC = (_, props) => props.c\r\n\r\n// state only (props argument omitted as not required)\r\nconst selectD = state => state.d\r\n\r\nconst totalSelector = createSelector(\r\n  selectAB,\r\n  selectC,\r\n  selectD,\r\n  (ab, c, d) => ({\r\n    total: ab + c + d\r\n  })\r\n)\r\n```\r\n\r\n### defaultMemoize(func, equalityCheckOrOptions = defaultEqualityCheck)\r\n\r\n`defaultMemoize` memoizes the function passed in the func parameter. It is the memoize function used by `createSelector`.\r\n\r\n`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.\r\n\r\n`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:\r\n\r\n```js\r\nfunction defaultEqualityCheck(previousVal, currentVal) {\r\n  return currentVal === previousVal\r\n}\r\n```\r\n\r\n`defaultMemoize` also accepts an options object as its first argument instead of `equalityCheck`. The options object may contain:\r\n\r\n```ts\r\ninterface DefaultMemoizeOptions {\r\n  equalityCheck?: EqualityFn\r\n  resultEqualityCheck?: EqualityFn\r\n  maxSize?: number\r\n}\r\n```\r\n\r\nAvailable options are:\r\n\r\n- `equalityCheck`: used to compare the individual arguments of the provided calculation function\r\n- `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.\r\n- `maxSize`: the cache size for the selector. If `maxSize` is greater than 1, the selector will use an LRU cache internally\r\n\r\nThe returned memoized function will have a `.clearCache()` method attached.\r\n\r\n`defaultMemoize` can also be used with `createSelectorCreator` to create a new selector factory that always has the same settings for each selector.\r\n\r\n### createSelectorCreator(memoize, ...memoizeOptions)\r\n\r\n`createSelectorCreator` can be used to make a customized version of `createSelector`.\r\n\r\nThe `memoize` argument is a memoization function to replace `defaultMemoize`.\r\n\r\nThe `...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:\r\n\r\n```js\r\nconst customSelectorCreator = createSelectorCreator(\r\n  customMemoize, // function to be used to memoize resultFunc\r\n  option1, // option1 will be passed as second argument to customMemoize\r\n  option2, // option2 will be passed as third argument to customMemoize\r\n  option3 // option3 will be passed as fourth argument to customMemoize\r\n)\r\n\r\nconst customSelector = customSelectorCreator(\r\n  input1,\r\n  input2,\r\n  resultFunc // resultFunc will be passed as first argument to customMemoize\r\n)\r\n```\r\n\r\nInternally `customSelector` calls the memoize function as follows:\r\n\r\n```js\r\ncustomMemoize(resultFunc, option1, option2, option3)\r\n```\r\n\r\nHere are some examples of how you might use `createSelectorCreator`:\r\n\r\n#### Customize `equalityCheck` for `defaultMemoize`\r\n\r\n```js\r\nimport { createSelectorCreator, defaultMemoize } from 'reselect'\r\nimport isEqual from 'lodash.isequal'\r\n\r\n// create a \"selector creator\" that uses lodash.isequal instead of ===\r\nconst createDeepEqualSelector = createSelectorCreator(defaultMemoize, isEqual)\r\n\r\n// use the new \"selector creator\" to create a selector\r\nconst selectSum = createDeepEqualSelector(\r\n  state => state.values.filter(val => val < 5),\r\n  values => values.reduce((acc, val) => acc + val, 0)\r\n)\r\n```\r\n\r\n#### Use memoize function from lodash for an unbounded cache\r\n\r\n```js\r\nimport { createSelectorCreator } from 'reselect'\r\nimport memoize from 'lodash.memoize'\r\n\r\nlet called = 0\r\nconst hashFn = (...args) =>\r\n  args.reduce((acc, val) => acc + '-' + JSON.stringify(val), '')\r\nconst customSelectorCreator = createSelectorCreator(memoize, hashFn)\r\nconst selector = customSelectorCreator(\r\n  state => state.a,\r\n  state => state.b,\r\n  (a, b) => {\r\n    called++\r\n    return a + b\r\n  }\r\n)\r\n```\r\n\r\n### createStructuredSelector({inputSelectors}, selectorCreator = createSelector)\r\n\r\n`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:\r\n\r\n```js\r\nconst selectA = state => state.a\r\nconst selectB = state => state.b\r\n\r\n// The result function in the following selector\r\n// is simply building an object from the input selectors\r\nconst structuredSelector = createSelector(selectA, selectB, (a, b) => ({\r\n  a,\r\n  b\r\n}))\r\n```\r\n\r\n`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.\r\n\r\n```js\r\nconst selectA = state => state.a\r\nconst selectB = state => state.b\r\n\r\nconst structuredSelector = createStructuredSelector({\r\n  x: selectA,\r\n  y: selectB\r\n})\r\n\r\nconst result = structuredSelector({ a: 1, b: 2 }) // will produce { x: 1, y: 2 }\r\n```\r\n\r\nStructured selectors can be nested:\r\n\r\n```js\r\nconst nestedSelector = createStructuredSelector({\r\n  subA: createStructuredSelector({\r\n    selectorA,\r\n    selectorB\r\n  }),\r\n  subB: createStructuredSelector({\r\n    selectorC,\r\n    selectorD\r\n  })\r\n})\r\n```\r\n\r\n## FAQ\r\n\r\n### Q: Why isn’t my selector recomputing when the input state changes?\r\n\r\nA: 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](http://redux.js.org/docs/Troubleshooting.html).\r\n\r\nThe following example defines a simple selector that determines if the first todo item in an array of todos has been completed:\r\n\r\n```js\r\nconst selectIsFirstTodoComplete = createSelector(\r\n  state => state.todos[0],\r\n  todo => todo && todo.completed\r\n)\r\n```\r\n\r\nThe following state update function **will not** work with `selectIsFirstTodoComplete`:\r\n\r\n```js\r\nexport default function todos(state = initialState, action) {\r\n  switch (action.type) {\r\n    case COMPLETE_ALL:\r\n      const areAllMarked = state.every(todo => todo.completed)\r\n      // BAD: mutating an existing object\r\n      return state.map(todo => {\r\n        todo.completed = !areAllMarked\r\n        return todo\r\n      })\r\n\r\n    default:\r\n      return state\r\n  }\r\n}\r\n```\r\n\r\nThe following state update function **will** work with `selectIsFirstTodoComplete`:\r\n\r\n```js\r\nexport default function todos(state = initialState, action) {\r\n  switch (action.type) {\r\n    case COMPLETE_ALL:\r\n      const areAllMarked = state.every(todo => todo.completed)\r\n      // GOOD: returning a new object each time with Object.assign\r\n      return state.map(todo =>\r\n        Object.assign({}, todo, {\r\n          completed: !areAllMarked\r\n        })\r\n      )\r\n\r\n    default:\r\n      return state\r\n  }\r\n}\r\n```\r\n\r\nIf 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](#use-memoize-function-from-lodash-for-an-unbounded-cache) and [here](#customize-equalitycheck-for-defaultmemoize) for examples.\r\n\r\n### Q: Why is my selector recomputing when the input state stays the same?\r\n\r\nA: 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.\r\n\r\n```js\r\nimport { REMOVE_OLD } from '../constants/ActionTypes'\r\n\r\nconst initialState = [\r\n  {\r\n    text: 'Use Redux',\r\n    completed: false,\r\n    id: 0,\r\n    timestamp: Date.now()\r\n  }\r\n]\r\n\r\nexport default function todos(state = initialState, action) {\r\n  switch (action.type) {\r\n    case REMOVE_OLD:\r\n      return state.filter(todo => {\r\n        return todo.timestamp + 30 * 24 * 60 * 60 * 1000 > Date.now()\r\n      })\r\n    default:\r\n      return state\r\n  }\r\n}\r\n```\r\n\r\nThe 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.\r\n\r\n```js\r\nimport { createSelector } from 'reselect'\r\n\r\nconst todosSelector = state => state.todos\r\n\r\nexport const selectVisibleTodos = createSelector(\r\n  todosSelector,\r\n  (todos) => {\r\n    ...\r\n  }\r\n)\r\n```\r\n\r\nYou 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:\r\n\r\n```js\r\nimport { REMOVE_OLD } from '../constants/ActionTypes'\r\nimport isEqual from 'lodash.isequal'\r\n\r\nconst initialState = [\r\n  {\r\n    text: 'Use Redux',\r\n    completed: false,\r\n    id: 0,\r\n    timestamp: Date.now()\r\n  }\r\n]\r\n\r\nexport default function todos(state = initialState, action) {\r\n  switch (action.type) {\r\n    case REMOVE_OLD:\r\n      const updatedState = state.filter(todo => {\r\n        return todo.timestamp + 30 * 24 * 60 * 60 * 1000 > Date.now()\r\n      })\r\n      return isEqual(updatedState, state) ? state : updatedState\r\n    default:\r\n      return state\r\n  }\r\n}\r\n```\r\n\r\nAlternatively, the default `equalityCheck` function in the selector can be replaced by a deep equality check:\r\n\r\n```js\r\nimport { createSelectorCreator, defaultMemoize } from 'reselect'\r\nimport isEqual from 'lodash.isequal'\r\n\r\nconst selectTodos = state => state.todos\r\n\r\n// create a \"selector creator\" that uses lodash.isequal instead of ===\r\nconst createDeepEqualSelector = createSelectorCreator(\r\n  defaultMemoize,\r\n  isEqual\r\n)\r\n\r\n// use the new \"selector creator\" to create a selector\r\nconst mySelector = createDeepEqualSelector(\r\n  todosSelector,\r\n  (todos) => {\r\n    ...\r\n  }\r\n)\r\n```\r\n\r\nAlways 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`.\r\n\r\n### Q: Can I use Reselect without Redux?\r\n\r\nA: 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 is currently being used successfully in traditional Flux apps.\r\n\r\n> If you create selectors using `createSelector` make sure its arguments are immutable.\r\n> See [here](#createselectorinputselectors--inputselectors-resultfunc)\r\n\r\n### Q: How do I create a selector that takes an argument?\r\n\r\nA: Keep in mind that selectors can access React props, so if your arguments are (or can be made available as) React props, you can use that functionality. [See here](#accessing-react-props-in-selectors) for details.\r\n\r\nOtherwise, Reselect doesn't have built-in support for creating selectors that accepts arguments, but here are some suggestions for implementing similar functionality...\r\n\r\nIf the argument is not dynamic you can use a factory function:\r\n\r\n```js\r\nconst expensiveItemSelectorFactory = minValue => {\r\n  return createSelector(shopItemsSelector, items =>\r\n    items.filter(item => item.value > minValue)\r\n  )\r\n}\r\n\r\nconst selectSubtotal = createSelector(\r\n  expensiveItemSelectorFactory(200),\r\n  items => items.reduce((acc, item) => acc + item.value, 0)\r\n)\r\n```\r\n\r\nThe general consensus [here](https://github.com/reduxjs/reselect/issues/38) and [over at nuclear-js](https://github.com/optimizely/nuclear-js/issues/14) is that if a selector needs a dynamic argument, then that argument should probably be state in the store. If you decide that you do require a selector with a dynamic argument, then a selector that returns a memoized function may be suitable:\r\n\r\n```js\r\nimport { createSelector } from 'reselect'\r\nimport memoize from 'lodash.memoize'\r\n\r\nconst expensiveSelector = createSelector(\r\n  state => state.items,\r\n  items => memoize(minValue => items.filter(item => item.value > minValue))\r\n)\r\n\r\nconst expensiveFilter = expensiveSelector(state)\r\n\r\nconst slightlyExpensive = expensiveFilter(100)\r\nconst veryExpensive = expensiveFilter(1000000)\r\n```\r\n\r\n### Q: The default memoization function is no good, can I use a different one?\r\n\r\nA: We think it works great for a lot of use cases, but sure. See [these examples](#customize-equalitycheck-for-defaultmemoize).\r\n\r\n### Q: How do I test a selector?\r\n\r\nA: For a given input, a selector should always produce the same output. For this reason they are simple to unit test.\r\n\r\n```js\r\nconst selector = createSelector(\r\n  state => state.a,\r\n  state => state.b,\r\n  (a, b) => ({\r\n    c: a * 2,\r\n    d: b * 3\r\n  })\r\n)\r\n\r\ntest('selector unit test', () => {\r\n  assert.deepEqual(selector({ a: 1, b: 2 }), { c: 2, d: 6 })\r\n  assert.deepEqual(selector({ a: 2, b: 3 }), { c: 4, d: 9 })\r\n})\r\n```\r\n\r\nIt 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:\r\n\r\n```js\r\nsuite('selector', () => {\r\n  let state = { a: 1, b: 2 }\r\n\r\n  const reducer = (state, action) => ({\r\n    a: action(state.a),\r\n    b: action(state.b)\r\n  })\r\n\r\n  const selector = createSelector(\r\n    state => state.a,\r\n    state => state.b,\r\n    (a, b) => ({\r\n      c: a * 2,\r\n      d: b * 3\r\n    })\r\n  )\r\n\r\n  const plusOne = x => x + 1\r\n  const id = x => x\r\n\r\n  test('selector unit test', () => {\r\n    state = reducer(state, plusOne)\r\n    assert.deepEqual(selector(state), { c: 4, d: 9 })\r\n    state = reducer(state, id)\r\n    assert.deepEqual(selector(state), { c: 4, d: 9 })\r\n    assert.equal(selector.recomputations(), 1)\r\n    state = reducer(state, plusOne)\r\n    assert.deepEqual(selector(state), { c: 6, d: 12 })\r\n    assert.equal(selector.recomputations(), 2)\r\n  })\r\n})\r\n```\r\n\r\nAdditionally, 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.\r\n\r\nFor example if you have a set of selectors like this:\r\n\r\n**selectors.js**\r\n\r\n```js\r\nexport const selectFirst = createSelector( ... )\r\nexport const selectSecond = createSelector( ... )\r\nexport const selectThird = createSelector( ... )\r\n\r\nexport const myComposedSelector = createSelector(\r\n  selectFirst,\r\n  selectSecond,\r\n  selectThird,\r\n  (first, second, third) => first * second < third\r\n)\r\n```\r\n\r\nAnd then a set of unit tests like this:\r\n\r\n**test/selectors.js**\r\n\r\n```js\r\n// tests for the first three selectors...\r\ntest(\"selectFirst unit test\", () => { ... })\r\ntest(\"selectSecond unit test\", () => { ... })\r\ntest(\"selectThird unit test\", () => { ... })\r\n\r\n// We have already tested the previous\r\n// three selector outputs so we can just call `.resultFunc`\r\n// with the values we want to test directly:\r\ntest(\"myComposedSelector unit test\", () => {\r\n  // here instead of calling selector()\r\n  // we just call selector.resultFunc()\r\n  assert(myComposedSelector.resultFunc(1, 2, 3), true)\r\n  assert(myComposedSelector.resultFunc(2, 2, 1), false)\r\n})\r\n```\r\n\r\nFinally, each selector has a `resetRecomputations` method that sets\r\nrecomputations back to 0. The intended use is for a complex selector that may\r\nhave many independent tests and you don't want to manually manage the\r\ncomputation count or create a \"dummy\" selector for each test.\r\n\r\n### Q: How do I use Reselect with Immutable.js?\r\n\r\nA: Selectors created with `createSelector` should work just fine with Immutable.js data structures.\r\n\r\nIf your selector is recomputing and you don't think the state has changed, make sure you are aware of which Immutable.js update methods **always** return a new object and which update methods only return a new object **when the collection actually changes**.\r\n\r\n```js\r\nimport Immutable from 'immutable'\r\n\r\nlet myMap = Immutable.Map({\r\n  a: 1,\r\n  b: 2,\r\n  c: 3\r\n})\r\n\r\n// set, merge and others only return a new obj when update changes collection\r\nlet newMap = myMap.set('a', 1)\r\nassert.equal(myMap, newMap)\r\nnewMap = myMap.merge({ a: 1 })\r\nassert.equal(myMap, newMap)\r\n// map, reduce, filter and others always return a new obj\r\nnewMap = myMap.map(a => a * 1)\r\nassert.notEqual(myMap, newMap)\r\n```\r\n\r\nIf a selector's input is updated by an operation that always returns a new object, it may be performing unnecessary recomputations. See [here](#q-why-is-my-selector-recomputing-when-the-input-state-stays-the-same) for a discussion on the pros and cons of using a deep equality check like `Immutable.is` to eliminate unnecessary recomputations.\r\n\r\n### Q: Can I share a selector across multiple component instances?\r\n\r\nA: 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:\r\n\r\n- Create a factory function which returns a new selector for each instance of the component. There is built-in support for factory functions in React Redux v4.3 or higher. See [here](#sharing-selectors-with-props-across-multiple-component-instances) for an example.\r\n\r\n- Create a custom selector with a cache size greater than one.\r\n\r\n### Q: Are there TypeScript Typings?\r\n\r\nA: Yes! Reselect is now written in TS itself, so they should Just Work™.\r\n\r\n### Q: How can I make a [curried](https://github.com/hemanth/functional-programming-jargon#currying) selector?\r\n\r\nA: Try these [helper functions](https://github.com/reduxjs/reselect/issues/159#issuecomment-238724788) courtesy of [MattSPalmer](https://github.com/MattSPalmer)\r\n\r\n## Related Projects\r\n\r\n### [re-reselect](https://github.com/toomuchdesign/re-reselect)\r\n\r\nEnhances Reselect selectors by wrapping `createSelector` and returning a memoized collection of selectors indexed with the cache key returned by a custom resolver function.\r\n\r\nUseful to reduce selectors recalculation when the same selector is repeatedly called with one/few different arguments.\r\n\r\n### [reselect-tools](https://github.com/skortchmark9/reselect-tools)\r\n\r\n[Chrome extension](https://chrome.google.com/webstore/detail/reselect-devtools/cjmaipngmabglflfeepmdiffcijhjlbb?hl=en) and [companion lib](https://github.com/skortchmark9/reselect-tools) for debugging selectors.\r\n\r\n- Measure selector recomputations across the app and identify performance bottlenecks\r\n- Check selector dependencies, inputs, outputs, and recomputations at any time with the chrome extension\r\n- Statically export a JSON representation of your selector graph for further analysis\r\n\r\n### [reselect-debugger](https://github.com/vlanemcev/reselect-debugger-flipper)\r\n\r\n[Flipper plugin](https://github.com/vlanemcev/flipper-plugin-reselect-debugger) and [and the connect app](https://github.com/vlanemcev/reselect-debugger-flipper) for debugging selectors in **React Native Apps**.\r\n\r\nInspired by Reselect Tools, so it also has all functionality from this library and more, but only for React Native and Flipper.\r\n\r\n- Selectors Recomputations count in live time across the App for identify performance bottlenecks\r\n- Highlight most recomputed selectors\r\n- Dependency Graph\r\n- Search by Selectors Graph\r\n- Selectors Inputs\r\n- Selectors Output (In case if selector not dependent from external arguments)\r\n- Shows \"Not Memoized (NM)\" selectors\r\n\r\n### [reselect-map](https://github.com/HeyImAlex/reselect-map)\r\n\r\nCan be useful when doing **very expensive** computations on elements of a collection because Reselect might not give you the granularity of caching that you need. Check out the reselect-maps README for examples.\r\n\r\n**The optimizations in reselect-map only apply in a small number of cases. If you are unsure whether you need it, you don't!**\r\n\r\n## License\r\n\r\nMIT\r\n\r\n[build-badge]: https://img.shields.io/github/workflow/status/reduxjs/redux-thunk/Tests\r\n[build]: https://github.com/reduxjs/reselect/actions/workflows/build-and-test-types.yml\r\n[npm-badge]: https://img.shields.io/npm/v/reselect.svg?style=flat-square\r\n[npm]: https://www.npmjs.org/package/reselect\r\n[coveralls-badge]: https://img.shields.io/coveralls/reduxjs/reselect/master.svg?style=flat-square\r\n[coveralls]: https://coveralls.io/github/reduxjs/reselect\r\n","authors":["Lee Bannard","Robert Binna","Martijn Faassen","Philip Spitzlinger"],"gitHead":"a94302d37d902acb3db8a4e82392efe4936a2f13","scripts":{"lint":"eslint src test","test":"jest","build":"rimraf dist lib es && npm run build:types && npm run build:commonjs && npm run build:es && npm run build:umd && npm run build:umd:min","clean":"rimraf lib dist es coverage","format":"prettier --write \"{src,test}/**/*.{js,ts}\" \"docs/**/*.md\"","build:es":"babel src/*.ts --ignore src/types.ts --extensions .ts --out-dir es","test:cov":"jest --coverage","api-types":"api-extractor run --local","build:umd":"cross-env NODE_ENV=development rollup -c -o dist/reselect.js","build:types":"tsc","build:umd:min":"cross-env NODE_ENV=production rollup -c -o dist/reselect.min.js","build:commonjs":"cross-env BABEL_ENV=commonjs babel src/*.ts --ignore src/types.ts --extensions .ts --out-dir lib ","prepublishOnly":"npm run build","test:typescript":"better-npm-run test:typescript"},"_npmUser":{"name":"acemarke","email":"mark.erikson@gmail.com"},"repository":{"url":"git+https://github.com/reduxjs/reselect.git","type":"git"},"_npmVersion":"6.14.7","description":"Selectors for Redux.","directories":{},"jsnext:main":"./es/index.js","sideEffects":false,"_nodeVersion":"14.17.0","dependencies":{},"betterScripts":{"test":{"env":{"NODE_ENV":"test"},"command":"mocha --compilers js:@babel/register --ui tdd --recursive"},"test:cov":{"env":{"COVERAGE":"true","NODE_ENV":"test"},"command":"nyc --reporter=lcov --reporter=text mocha --compilers js:@babel/register --ui tdd"},"test:typescript":{"command":"tsc --noEmit -p typescript_test/tsconfig.json"},"compile:commonjs":{"env":{"BABEL_ENV":"cjs"},"command":"babel -d lib/ src/"}},"typesVersions":{"<4.2":{"*":["./src/typesVersions/ts4.1/index.d.ts"]}},"_hasShrinkwrap":false,"readmeFilename":"README.md","devDependencies":{"ncp":"^2.0.0","nyc":"^15.1.0","chai":"^4.3.4","jest":"^27.3.1","mocha":"^9.1.3","eslint":"^8.0.1","mkdirp":"^1.0.4","rollup":"^2.58.0","tslint":"6.1.3","ts-jest":"27.0.7","prettier":"^2.4.1","coveralls":"^3.1.1","cross-env":"^7.0.3","@babel/cli":"^7.15.7","codecov.io":"^0.1.6","typescript":"^4.4.0","@babel/core":"^7.15.8","@types/jest":"^27.0.2","memoize-one":"^6.0.0","@types/lodash":"^4.14.175","micro-memoize":"^4.0.9","better-npm-run":"0.1.1","lodash.memoize":"^4.1.2","@babel/register":"^7.15.3","@babel/preset-env":"^7.15.8","eslint-plugin-react":"^7.26.1","@rollup/plugin-babel":"^5.3.0","rollup-plugin-terser":"^7.0.2","@rollup/plugin-replace":"^3.0.0","@rollup/plugin-commonjs":"^21.0.1","@babel/preset-typescript":"^7.15.0","@microsoft/api-extractor":"^7.18.16","eslint-plugin-typescript":"0.14.0","@typescript-eslint/parser":"5.1.0","@rollup/plugin-node-resolve":"^13.0.6","@typescript-eslint/eslint-plugin":"5.1.0","@typescript-eslint/eslint-plugin-tslint":"5.1.0"},"_npmOperationalInternal":{"tmp":"tmp/reselect_4.1.0-beta.2_1635099982808_0.7539559850963313","host":"s3://npm-registry-packages"},"publish_time":1635099983036,"_cnpm_publish_time":1635099983036,"dist-tags":{"alpha":"5.0.0-alpha.2","beta":"5.0.0-beta.1","latest":"5.3.0","next":"5.0.0-rc.0","rc":"5.0.0-rc.1","rc1":"3.0.0-beta.1"}}