reselect
reselect copied to clipboard
Memoization works too well with composed selectors
It seems that composed selectors create unpredictable updates when composed. Or, rather, my views don't update when I update data in my store that is memoized more than once through the composition chain of selectors.
For example:
let selector1 = createSelector(/*...*/)
let selector2 = createSelector(
[
selector1,
state => state.something
],
(selector1Stuff, something) => {
return {
selector1Stuff,
something
};
}
);
If data in selector1 should be updated, it should trigger the update or anything composing with it.
Running the following works as I would expect:
import { createSelector } from 'reselect';
let selector1 = createSelector(
state => state.a,
a => a
);
let selector2 = createSelector(
[
selector1,
state => state.b
],
(selector1Stuff, something) => {
console.log(`recomputing (selector1Stuff = ${selector1Stuff}, something = ${something})`);
return {
selector1Stuff,
something
};
}
);
const state1 = {a: 1, b: 2};
const state2 = {a: 3, b: 2};
selector2(state1);
selector2(state1);
selector2(state2);
selector2(state2);
selector2(state2);
selector2(state1);
Can you create a simple test case demonstrating the problem?
I spent some time writing the following test, and it passes. Looks like it's my logic. Sorry about that.
test("composed selectors handle memoization correctly", function() {
let called1 = 0;
let called2 = 0;
let called3 = 0;
const selector1 = createSelector([state => state.one], one => {
called1++;
return one;
});
const selector2 = createSelector(
[
selector1,
state => state.two
],
(one, two) => {
called2++;
return {
one,
two
};
}
);
const selector3 = createSelector(
[
selector1,
selector2,
state => state.three
],
(one, two, three) => {
called3++;
return {
one,
two,
three
};
}
);
let result1 = selector3({
one: 1,
two: 2,
three: 3
});
let result2 = selector3({
one: 11,
two: 2,
three: 3
});
assert.deepEqual(result1, {
one: 1,
two: {
one: 1,
two: 2
},
three: 3
});
assert.deepEqual(result2, {
one: 11,
two: {
one: 11,
two: 2
},
three: 3
});
});