A store subscribe function that checks if state has changed before trigger.
Supports modern browsers and IE9+:
npm install immutable-merge-operators --save
❗ Pro Tip: Use Yarn to install dependencies 3x faster than NPM!
yarn add immutable-merge-operators
As you can check here, in Redux, store's subscribe method should not be used directly because it's a low level API. The store API is meant to be extensible, so Dan did it simple as possible. The thing is that your subscribe method will trigger everytime the dispatch method is called, not everytime the store changes. redux-pure-subscribe is a post-execution pull that checks if some part of your state has changed before triggers and then calls the cb function. OBS: We use a shallow comparison algorithm with object/array reference equality check (its fast!), so you may need some immutable lib like immutable-merge-operators
I'ts actually very simple, you just need to import and use passing the store as first argument and a cb function as second.
import pureSubscribe from 'redux-pure-subscribe';
pureSubscribe(store, callback);
redux-pure-subscribe passes the store current state as an argument to the cb function, so its easier for you to use it.
const callback = function(state) {
const cats = state.myCats;
};
pureSubscribe(store, callback);
You can also use object destruction and make it funnier
const callback = function({myCats, myDogs, myBirds}) {
const pets = {myCats, myDogs, myBirds}
};
pureSubscribe(store, callback);
You can also pass an array of trees you want to observe for changes, so if your component should only trigger when specifics parts of your state changes, you can pass it as a third parameter
pureSubscribe(store, callback, 'myCats'); // We also accept a strig in case you just want to observe one path
redux-pure-subscribe will trigger the cb function at least once to get the initial state from store, so you wont need to do this anymore:
callback();
pureSubscribe(store, callback);