reusing selectors which memoize correctly around props
In order to improve performance of my selectors which rely on the props of a component I'm using the approach described here.
The problem I'm facing is: I have two selectors A and B, and I use both of them in my component. But, selector A also uses selector B, so even though I memoize them properly in my makeMapStateToProps function selector B (let's assume it's doing something expensive) will still run twice: once when I run use it in my component, and again in the implementation of selector A.
Are there any approaches to workaround this limitation?
Hey @simoneb, do you have some example code that I could run?
Hey @ellbee, see below.
I have expensiveSelector which gets two arguments and does some expensive computation with them, so I want to memoize it.
selectorA uses reselect and provides inputs for expensiveSelector and because inputs come also from props I expose a function to create it, makeSelectorA
const expensiveSelector = (some, data) => /* something expensive happening here */
const makeSelectorA = () => createSelector([selectSome, selectData], expensiveSelector)
Now suppose that I need a selectorA somewhere else, for instance in a selectorB, how do I create a shared instance which is shared among all those who will have the same prop values?
@simoneb I've been considering similar questions. The selector is just a regular function produced by your factory (the make function). So depending on how your code works, you could instantiate it once and pass it around so it's reused.
For example, instead of makeSelectorA you could have makeSelectors which creates one instance of expensiveSelector and then uses that one instance in two separate calls to createSelector().
At least, that's my best guess! :-)
@chmac thanks for your reply! I realized I was basically searching for a chimera as we're just dealing with regular functions, so usual concepts of compositions apply with no other magic involved. Thanks for clearing that up 😄