JSPM

  • Created
  • Published
  • Downloads 1718
  • Score
    100M100P100Q109989F
  • License MIT

The right memoization for redux's mapStateToProps

Package Exports

  • memoize-state

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (memoize-state) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

memoize-state

Reselect? Memoize-one? It is quite hard to debug how mapStateToProps behave.

You know - it should be a pure function, returning the same results for the same arguments. mapStateToProps, should be strict equal across the different calls

mapStateToProps(state) === mapStateToProps(state)

or, at least, shallow equal. Actually this is the case, redux expects

shallowEqual(mapStateToProps(state), mapStateToProps(state)).

But it does not.

Most of memoizations works as selectors, making a new result to be shallowequal to the old one, to prevent unnecessary redraw.

Memoize-state memoized used state, using the same magic, as you can found in MobX. And, you know, you can use it to memoize any function.

NPM

Key principe

 const state = {
   branch1: {...},
   branch2: {someKey1:1, someKey2: 2}
 }
 
 const aFunction = (state) => state.branch2.someKey2 && Math.random();
 
 const fastFunction = memoize(aFunction);
 

After the first launch memoize-state will detect the used parts of a state, and then react only for changes inside them

 const result1 = fastFunction(state); 
 // result1 - some random. 42 for example
 const result2 = fastFunction({branch2: {someKey2:2}})
 // result2 - the same value! A new state is `proxyequal` to the old
 const result3 = fastFunction({branch2: {someKey2:3}})
 // result3 - is the NEW, at last.   

Usage

  • Wrap mapStateToProps by memoize
  • Choose the memoization count (1 by default).
import memoize from 'memoize-state';

const mapStateToProps = memoize((state, props) => {
  ....
});

You also could use memoize-state to double check your selectors.

import {shouldBePure} from 'memoize-state';

const mapStateToProps = shouldBePure((state, props) => {
  ....
});
// then it will log all situations, when result was not shallow equal to the old one, but should.

shouldBePure will deactive itself in production env. Use shallBePure if you need it always enabled.

Speed

Uses ES6 Proxy underneath to detect used branches of a state (as MobX). Should be slower than "manual" __reselect__ors, but faster than anything else.

Compatibility

NOT compatible with IE11. One need to provide a proxy polyfill to make this work. See https://github.com/GoogleChrome/proxy-polyfill

Licence

MIT