Does not memoize correctly when filtering by ownProps
Hello,
I found a situation in witch reselect does not memoize correctly when filtering by ownProps.
The scenario is as following: We want a component that computes total amount based on year.
-
State:
[{Year : 2018, Amount: 21}, {Year : 2018, Amount: 21}, {Year : 2017, Amount: 42},] -
A selector that an accepts year from ownProps and computes the total amount for that year
function getStateList(state) {
return state;
}
const getFilteredState = (state, props) => getStateList(state).filter(s => s.Year === props.year);
function makeGetTotalAmount() {
return createSelector(
[getFilteredState],
(list) => {
return list.reduce((acc, curr) => {
return acc + curr.Amount;
}, 0)
}
);
}
export default makeGetTotalAmount;
- Two instances of a TotalAmount.js component, each accepting the year as props
<TotalAmount year={2018} />
<TotalAmount year={2017} />
- And a makeMapStateToProps in TotalAmount.js component
const makeMapStateToProps = () => {
const getTotalAmount = selectors.makeGetTotalAmount();
const mapStateToProps = (state, props) => {
return {
totalAmount: getTotalAmount (state, props),
}
};
return mapStateToProps;
}
My state is normalized and this seems like a common issue, in my projects at least. I think the problem is that filter creates a new array instance every time, but there is no apparent workaround and the documentation is not clear on what to do in these kind of scenarios.
Thank you very much for the time and effort!
Yes, the problem is that your getFilteredState() selector is returning a new array instance every time, so Reselect will always run the "output selector" you provided.
The answer is to use Reselect to create getFilteredState as well. You may also need to change it so that instead of directly using props.year, it accepts year as a separate argument, roughly like this:
const selectYear = (state, props) => props.year;
const getFilteredState = createSelector(
[getStateList, selectYear],
(stateList, year) => stateList.filter(s => s.Year === year)
);
Thank you very much for your fast response!
Unfortunately I could not make that run. It recomputes unnecessarily on all other store changes (in the real world project where the store is more than the list). The getStateList and selectYear did not seem to change, but filter is still being called.
My foolish way of checking for equality was to add this code to the one that you provided:
const getFilteredState = createSelector(
[getStateList, selectYear],
(stateList, year) => {
let rand = Math.floor(Math.random() * 100); // Get a random number 0 - 100
console.log(rand); // Print it in the console so I can use it later
window["arr" + rand] = stateList;
window["year" + rand] = year;
return stateList.filter(s => s.Year === year); }
);
Run the application to receive a number (let's say 10) and then mutate some other part of the state (let's say 40) and use the console to compute "arr10 === arr40 && year10 === year40" // true.
From what I've read the last function should not be called in that situation.
In my application the stateList is behind a redux-undo. Something like:
function getStateList(state) {
return state.....present.amountsByYear;
}
But since present is changing, but amountsByYear is not changing this should not be a problem in my opinion.
Ultimately, you need to make sure that the values returned by the "input selectors" are only changing if the parameters to the result selector have changed. Reselect will then re-run the "output selector" whenever the "input selectors" return new values.
I've managed to make a little example to replicate it. (All the reselect code is at TotalAmount.js)
https://codesandbox.io/s/wn7kjxvp3l
The console log shows two times "foo2018", but I expect it to be called only once.
Yes, in that example, the state value itself is always changing, therefore the value being returned by getStateList() always changes, therefore the filter statement always runs. The selector logic appears to be working as intended. (Although I don't see the "UPDATE" action being dispatched anywhere?)
Also, that example has two different "2018" components, which may be affecting things.
Actually the state is never changing. And I wanted to highlight that. There are no actions being dispatched and you work only with the default value for the reducer. The second "2018" component is there to show that although the values in the state and props are the same the re-selector is being called twice.
Maybe I have confused you with the UPDATE action, but it is never being called and without it the code works the same way. I have modified the code so the reducer just returns the same result no matter what.
Aha. Okay, that's why.
It's because getFilteredState is being called with different inputs one after the other.
It's called with:
(state, 2018)(state, 2017)(state, 2018)
So, it never sees the same two inputs twice in a row, and therefore doesn't memoize properly. Try changing the order so that the components are 2018 / 2018 / 2017. You'll see that "foo2018" only shows up once, because the order of the components is different, and so the order of calls to getFilteredState is different. The two 2018 calls will be back-to-back, so it will skip the run the second time.
I talked about this in my post Idiomatic Redux: Using Reselect Selectors for Encapsulation and Performance.
Wow that is a tremendous work that you have put into that blog post! Thank you for that!
But if I read it correctly, the conclusion that is drawn is that you can use "factory functions" for mapStateToProps a.k.a makeMapStateToProps to properly memorize the selectors. And I believe that this is what I am doing in the example in CodeSandbox. (Please also note that when switching the places of 2017 and the second 2018 component the "foo2018" is called once, but "bar" is called three times).
Also there are cases when you want to use the same selectors for different interfaces. For example there might be a component that displays the total amounts for years in tabular fashion and another one that displays them in a pie chart. Thus the selectors will never be called paired by type.
Is there a solution for this issue?
Ultimately, in order for memoization to work properly, you need to have consistent inputs to each function involved.
At the moment, you're creating a unique instance for getTotalAmount(), but not for getFilteredState().
You could potentially have a makeGetFilteredState() factory, and call that inside of makeGetTotalAmount() to have a unique instance of getFilteredState for that instance of getTotalAmount.
That makes sense, but when I am trying it the result is the same. For Example: https://codesandbox.io/s/l5zkvvy50q
Console was cleared
TotalAmount.js:55 foo2018
TotalAmount.js:66 bar
TotalAmount.js:55 foo2017
TotalAmount.js:66 bar
TotalAmount.js:55 foo2018
TotalAmount.js:66 bar
If you could provide a working example, that would be great
@gyosifov The console log that you have does not show that the selector has recomputed 3 times. It shows that the selector has been instantiated 3 times. 3 console logs should be the expected behavior.
If you remove the first <TotalAmount year={2018} /> you will get 2 console logs:
TotalAmount.js:55 foo2017
TotalAmount.js:66 bar
TotalAmount.js:55 foo2018
TotalAmount.js:66 bar
For future reference, you can use the recommendations method to determine whether your selector is memoized correctly.
For anyone struggling with selector.recomputations() = 0 for all console logs (or however you're testing/debugging), make sure to instantiate the selector inside of a "makeMapStateToProps" factory like:
function makeMapStateToProps() {
const selector = makeSelector();
return function mapStateToProps(state, props) {
console.log(selector.recomputations();
return {
foo: selector(state, props)
};
}
}
@drewandrew You have to have two components of a kind to test if the memoization is correct. Therefore the first <TotalAmount year={2018} /> is necessary. I have to disagree with you about the console.log. If you see the text it means that all of the other /expensive/ computations in the body of the selector will also be executed.
@gyosifov I believe that the problem in https://codesandbox.io/s/wn7kjxvp3l is that by having two <TotalAmount year={2018} /> you are actually creating two instances of this component, therefore creating two calls to makeMapStateToProps and makeGetTotalAmount. Each makeGetTotalAmount call will create a new selector with a different memoized set of arguments. Although they have the same value, they are not the same objects.
Yes, I think you are correct, My question is in a situation with a state like this is there any way using reselect to memoize the selectors.
Hi @gyosifov.
I created an alternative library called recompute that might solve your use case.
I forked your sandbox with my solution using recompute: https://codesandbox.io/s/reselect-issues-375-1gsvs