Skip to content

Enhance Reselect selectors with deeper memoization and cache management.

License

Notifications You must be signed in to change notification settings

laurent22/re-reselect

ย 
ย 

Repository files navigation

Re-reselect

Build status Npm version Npm downloads Test coverage report

re-reselect is a lightweight wrapper around Reselect meant to enhance selectors with deeper memoization and cache management.

Switching between different arguments using standard reselect selectors causes cache invalidation since default reselect cache has a limit of one.

re-reselect forwards different calls to different reselect selectors stored in cache, so that computed/memoized values are retained.

re-reselect selectors work as normal reselect selectors but they are able to determine when creating a new selector or querying a cached one on the fly, depending on the supplied arguments.

Reselect and re-reselect

Useful to:

import createCachedSelector from 're-reselect';

// Normal reselect routine: declare "inputSelectors" and "resultFunc"
const selectorA = state => state.a;
const selectorB = (state, itemName) => state.items[itemName];

const cachedSelector = createCachedSelector(
  // inputSelectors
  selectorA,
  selectorB,

  // resultFunc
  (A, B) => expensiveComputation(A, B)
)(
  // keySelector
  // Instruct re-reselect to use "itemName" as cacheKey
  (state, itemName) => itemName
);

// Use the cached selector like a normal selector:
const fooResult = cachedSelector(state, 'foo');
const barResult = cachedSelector(state, 'bar');

// 2 reselect selectors were created, called and cached behind the scenes

const fooResultAgain = cachedSelector(state, 'foo');

// fooResult === fooResultAgain
// Cache was not invalidated by calling "cachedSelector(state, 'bar')"
// "expensiveComputation" totally called twice

Table of contents

Installation

npm install reselect -S
npm install re-reselect -S

Why? + example

I found myself wrapping a library of data elaboration (quite heavy stuff) with reselect selectors (getPieceOfData in the example).

On each store update, I had to repeatedly call the selector in order to retrieve all the pieces of data needed by my UI. Like this:

getPieceOfData(state, itemId, 'dataA');
getPieceOfData(state, itemId, 'dataB');
getPieceOfData(state, itemId, 'dataC');

What happens, here? getPieceOfData selector cache is invalidated on each call because of the different 3rd 'dataX' argument.

re-reselect solution

re-reselect selectors keep a cache of reselect selectors and store/retrieve them by cacheKey.

cacheKey is by default a string or number but can be anything depending on the chosen cache strategy (see cache objects docs).

cacheKey is the output of keySelector, declared at selector initialization.

keySelector is a custom function which:

  • takes the same arguments as the final selector (in the example: state, itemId, 'dataX')
  • returns a cacheKey.

Note that the same reselect selector instance stored in cache will be used for computing data for the same cacheKey (1:1).

Back to the example, re-reselect retrieves data by querying one of the cached selectors using the 3rd argument as cacheKey, allowing cache invalidation only when state or itemId change (but not dataType):

const getPieceOfData = createCachedSelector(
  state => state,
  (state, itemId) => itemId,
  (state, itemId, dataType) => dataType,
  (state, itemId, dataType) => expensiveComputation(state, itemId, dataType)
)(
  (state, itemId, dataType) => dataType // Use dataType as cacheKey
);

createCachedSelector returns a selector with the same signature as a normal reselect selector.

But now, each time the selector is called, the following happens behind the scenes:

  1. Evaluate the cacheKey for current call by executing keySelector
  2. Retrieve from cache the reselect selector stored under the given cacheKey
  3. Return found selector or create a new one if no selector was found
  4. Call returned selector with provided arguments

re-reselect stays completely optional and consumes your installed reselect module (reselect is declared as peer dependency).

Other viable solutions

1- Declare a different selector for each different call

Easy, but doesn't scale. See "join similar selectors" example.

2- Declare a makeGetPieceOfData selector factory as explained in Reselect docs

The solution suggested in Reselect docs is fine, but it has a few downsides:

  • Bloats your code by exposing both get selectors and makeGet selector factories
  • Needs to import/call selector factory instead of directly using selector
  • Two different instances given the same arguments, will individually store and recompute the same result (read this)

3- Wrap your makeGetPieceOfData selector factory into a memoizer function and call the returning memoized selector

This is what re-reselect actually does! :-) It's quite verbose (since has to be repeated for each selector), that's why re-reselect is here.

Examples

FAQ

How do I wrap my existing selector with re-reselect?

Given your reselect selectors:

import {createSelector} from 'reselect';

export const getMyData = createSelector(
  selectorA,
  selectorB,
  selectorC,
  (A, B, C) => doSomethingWith(A, B, C)
);

...add keySelector in the second function call:

import createCachedSelector from 're-reselect';

export const getMyData = createCachedSelector(
  selectorA,
  selectorB,
  selectorC,
  (A, B, C) => doSomethingWith(A, B, C)
)(
  (state, arg1, arg2) => arg2 // Use arg2 as cacheKey
);

Voilร , getMyData is ready for use!

const myData = getMyData(state, 'foo', 'bar');
How do I use multiple inputs to set the cacheKey?

A few good examples and a bonus:

// Basic usage: use a single argument as cacheKey
createCachedSelector(
  // ...
)(
  (state, arg1, arg2, arg3) => arg3
)

// Use multiple arguments and chain them into a string
createCachedSelector(
  // ...
)(
  (state, arg1, arg2, arg3) => `${arg1}:${arg3}`
)

// Extract properties from an object
createCachedSelector(
  // ...
)(
  (state, props) => `${props.a}:${props.b}`
)
How do I limit the cache size?

Use a cacheObject which provides that feature by supplying a cacheObject option.

You can also write your own cache strategy!

How to share a selector across multiple components while passing in props and retaining memoization?

This example shows how re-reselect would solve the scenario described in reselect docs. Read more about testing selectors on reselect docs.

How do I test a re-reselect selector?

Like a normal reselect selector!

re-reselect selectors expose the same reselect testing methods:

  • dependencies
  • resultFunc
  • recomputations
  • resetRecomputations

Read more about testing selectors on reselect docs.

Testing reselect selectors stored in the cache

Each re-reselect selector exposes a getMatchingSelector method which returns the underlying matching selector instance for the given arguments, instead of the result.

getMatchingSelector expects the same arguments as a normal selector call BUT returns the instance of the cached selector itself.

Once you get a selector instance you can call its public methods.

import createCachedSelector from 're-reselect';

export const getMyData = createCachedSelector(selectorA, selectorB, (A, B) =>
  doSomethingWith(A, B)
)(
  (state, arg1) => arg1 // cacheKey
);

// Call your selector
const myFooData = getMyData(state, 'foo');
const myBarData = getMyData(state, 'bar');

// Call getMatchingSelector method to retrieve underlying reselect selectors
// which generated "myFooData" and "myBarData" results
const myFooDataSelector = getMyData.getMatchingSelector(state, 'foo');
const myBarDataSelector = getMyData.getMatchingSelector(state, 'bar');

// Call reselect's selectors methods
myFooDataSelector.recomputations();
myFooDataSelector.resetRecomputations();

API

createCachedSelector

import createCachedSelector from 're-reselect';

createCachedSelector(
  // ...reselect's `createSelector` arguments
)(
  keySelector,
  { options }
)

Takes the same arguments as reselect's createSelector and returns a new function which accepts 2 arguments:

  • keySelector
  • { options } (optional)

Returns a selector instance.

createStructuredCachedSelector

import { createStructuredCachedSelector } from 're-reselect';

createStructuredCachedSelector(
  // ...reselect's `createStructuredSelector` arguments
)(
  keySelector,
  { options }
)

Takes the same arguments as reselect's createStructuredSelector and returns a new function which accepts 2 arguments:

  • keySelector
  • { options } (optional)

Returns a selector instance.

keySelector

A custom function receiving the same arguments as your selectors (and inputSelectors) and returning a cacheKey.

cacheKey is by default a string or number but can be anything depending on the chosen cache strategy (see cacheObject option).

The keySelector idea comes from Lodash's .memoize resolver.

options

cacheObject

Type: object
Default: FlatObjectCache

An optional custom cache strategy object to handle the caching behaviour. Read more about re-reselect's custom cache here.

selectorCreator

Type: function
Default: reselect's createSelector

An optional function describing a custom version of createSelector.

keySelectorCreator

Type: function
Default: undefined

An optional function with the following signature returning the keySelector used by the cached selector.

export type keySelectorCreator = (selectorInputs: {
  inputSelectors: InputSelector[];
  resultFunc: ResultFunc;
  keySelector: KeySelector;
}) => KeySelector;

This allows to dynamically generate keySelectors on runtime based on provided inputSelectors/resultFunc supporting key selectors composition.

re-reselect selector instance

createCachedSelector and createStructuredCachedSelector return a selector instance which extends the API of a standard reselect selector.

The followings are advanced methods and you won't need them for basic usage!

selector.getMatchingSelector(selectorArguments)

Retrieve the selector responding to the given arguments.

selector.removeMatchingSelector(selectorArguments)

Remove from the cache the selector responding to the given arguments.

selector.cache

Get cacheObject instance being used by the selector (for advanced caching operations like this).

selector.clearCache()

Clear whole selector cache.

selector.dependencies

Get an array containing the provided inputSelectors. Refer to relevant discussion on Reselect repo.

selector.resultFunc

Get resultFunc for easily testing composed selectors.

selector.recomputations()

Return the number of times the selector's result function has been recomputed.

selector.resetRecomputations()

Reset recomputations count.

selector.keySelector

Get keySelector for utility compositions or testing.

About re-reselect

Todo's

  • Improve TS tests readability
  • More examples

Contributors

Thanks to you all (emoji key):

Andrea Carraro
Andrea Carraro

๐Ÿ’ป ๐Ÿ“– ๐Ÿš‡ โš ๏ธ ๐Ÿ‘€
Stepan Burguchev
Stepan Burguchev

๐Ÿ’ป ๐Ÿค” ๐Ÿ’ฌ ๐Ÿ‘€ โš ๏ธ
Sergei Grishchenko
Sergei Grishchenko

๐Ÿ’ป ๐Ÿค” โš ๏ธ ๐Ÿ”ง
Mateusz Burzyล„ski
Mateusz Burzyล„ski

๐Ÿ’ป ๐Ÿš‡
Mitch Robb
Mitch Robb

๐Ÿ’ป โš ๏ธ
Stephane Rufer
Stephane Rufer

๐Ÿ’ป โš ๏ธ
Tracy Mullen
Tracy Mullen

๐Ÿ’ป โš ๏ธ
Sushain Cherivirala
Sushain Cherivirala

๐Ÿ’ป
Steve Mao
Steve Mao

๐Ÿ“–
Gaurav Lahoti
Gaurav Lahoti

๐Ÿ›
Lon
Lon

๐Ÿ›
bratushka
bratushka

๐Ÿ’ป
Anders D. Johnson
Anders D. Johnson

๐Ÿ“–
Jรบlius Retzer
Jรบlius Retzer

๐Ÿ“–
Maarten Schumacher
Maarten Schumacher

๐Ÿค”
Alexander Jarvis
Alexander Jarvis

๐Ÿค”
Gregg B
Gregg B

๐Ÿ’ก
Ian Obermiller
Ian Obermiller

๐Ÿ‘€
Kanitkorn Sujautra
Kanitkorn Sujautra

๐Ÿ“–
Brian Kraus
Brian Kraus

๐Ÿ“–
el-dav
el-dav

๐Ÿ›
Augustin Riedinger
Augustin Riedinger

๐Ÿค”
RichardForrester
RichardForrester

๐Ÿค”

About

Enhance Reselect selectors with deeper memoization and cache management.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • TypeScript 50.8%
  • JavaScript 49.2%