reselect icon indicating copy to clipboard operation
reselect copied to clipboard

How to use reselect with Immutable.js?

Open gajus opened this issue 11 years ago • 37 comments

gajus avatar Aug 13 '15 12:08 gajus

import {
    createSelector
} from 'reselect';
import Immutable from 'immutable';

let state = {},
    taskSelector,
    activeTaskSelector;

state.tasks = [
    {
        id: 1,
        name: 'foo',
        done: true
    },
    {
        id: 2,
        name: 'bar',
        done: true
    },
    {
        id: 3,
        name: 'baz',
        done: false
    },
];

state = Immutable.fromJS(state);

taskSelector = state => state.get('tasks');

activeTaskSelector = createSelector(
    [
        taskSelector
    ],
    tasks => {
        return tasks.filter(task => task.get('done'));
    }
);

console.log( activeTaskSelector(state) === activeTaskSelector(state) );

A common pitfall is to use createSelectorCreator(Immutable.is) instead of simple createSelector. See the rest of the discussion.

gajus avatar Aug 13 '15 12:08 gajus

I figure this is the proper way. If I am wrong, someone please correct it. Otherwise, I have created this issue as a reference point.

gajus avatar Aug 13 '15 12:08 gajus

@gajus Could you please elaborate why should we use Immutable.is() as an equalsFn?

vovacodes avatar Aug 17 '15 14:08 vovacodes

@wizardzloy It is explained in the Immutable.js docs, https://facebook.github.io/immutable-js/docs/#/is.

var map1 = Immutable.Map({a:1, b:1, c:1});
var map2 = Immutable.Map({a:1, b:1, c:1});
assert(map1 !== map2);
assert(Object.is(map1, map2) === false);
assert(Immutable.is(map1, map2) === true);

gajus avatar Aug 17 '15 17:08 gajus

@gajus yes I saw that part of documentation, but I wonder why the simple === is not enough in case of selectors. I mean we suppose to use selector with the same state object I believe. So that if reference changed that means that the underlying data also changed. But Immutable.is() performs deep comparison which might introduce performance penalties. So my question is whether we really need to use it?

vovacodes avatar Aug 17 '15 18:08 vovacodes

Thats a good point. I will need to do a few tests.

gajus avatar Aug 17 '15 18:08 gajus

Immutable.js always returns a new collection when certain operations (filter, reduce etc.) are applied to a collection. If you are using one of those operations to update Immutable.js collections in your state, === will indicate that collection has changed every time even if nothing actually changes.

ellbee avatar Aug 17 '15 20:08 ellbee

@ellbee can you give an example in the context of reselect where that is relevant?

gajus avatar Aug 17 '15 21:08 gajus

If the EqualsFn thinks the arguments are different every single time the selector is called, the memoization isn't going to work. I guess it comes down to whether the cost of the deepEquals is greater than the cost of the computation in your selector.

ellbee avatar Aug 17 '15 21:08 ellbee

By the way, I think @wizardzloy is basically right and that === will often be the right thing to use. I just wanted to point out that depending on how you update a collection, an updated reference doesn't necessarily mean that the underlying data has changed.

ellbee avatar Aug 17 '15 21:08 ellbee

I think that === will always be the right thing to use even in the case when a selector is using filter or sort.

activeTaskSelector =createSelector(
    [
        taskSelector
    ],
    tasks => {
        return tasks.filter(task => task.get('done'));
    }
);

In this case, the selector will check taskSelector to see if it has changed. Since it is just reading from the store, === will determine if it has changed correctly. If it has changed, the selector will recompute the filter and memoize it. The next time that the selector is called, taskSelector will not have changed and so the memoized version will be returned, the filter will not be recomputed.

fooSelector = createSelector(
    [
        activeTaskSelector
    ],
    tasks => {
        return ...;
    }
);

Since the memoized version was returned, any composite filters down the line will also continue to work correctly. In this case, fooSelector will only be recomputed if activeTaskSelector was recomputed, which will only happen if taskSelector has changed, which is exactly what you want.

bunkat avatar Aug 17 '15 23:08 bunkat

@bunkat What if your reducer is updating the store using map, filter, reduce etc.?

ellbee avatar Aug 18 '15 06:08 ellbee

If your reducer updates the store (regardless of how it is done) the value will be different (=== will fail) and the selector will be recalculated which I think is what you would expect.

If your reducer updates the store with a strictly equivalent but new Immutable instance such that the selector would recalculate wastefully, I think that is a failure of the reducer (it should have just returned state in that case, not an updated state). I think it makes a lot more sense to do the equality check in the reducer (if that is a concern) rather than force all selectors to use Immutable.is which defeats a lot of the benefit of using immutables in the first place.

I actually can't imagine a scenario where a reducer would systematically be returning a strictly equivalent update as new state. That would mean that changes are happening outside of actions which shouldn't be the case, otherwise you would always know when running the map, filter, reduce would be necessary.

bunkat avatar Aug 18 '15 06:08 bunkat

I totally agree with @bunkat. As for me selectors should be as performant and easy to reason about as possible. So I believe that we should let the Immutable.js do its job of figuring out whether data actually changed and avoid adding this complexity into selectors. Should we somehow describe this in the README or create a gist?

vovacodes avatar Aug 18 '15 07:08 vovacodes

Yes, you can do a deep equality check in the reducer and not update the state if it hasn't changed, or you can check the state in the action to figure out whether you need to update, or if you prefer the mechanism is there so you can do it in the selector. All I wanted to point out in my original comment is that So that if reference changed that means that the underlying data also changed is not necessarily true when using Immutable's map, filter etc. and this can be surprising to some people because other operations (e.g. merge) do only return a new reference when the underlying data changes.

Also, each selector can be given a different equality function, so there is no need to force every selector to use Immutable.is().

ellbee avatar Aug 18 '15 07:08 ellbee

I am still missing a real life example of where Immutable.is would be useful in the context of reselect. Can you please contribute an example in code, @ellbee?

gajus avatar Aug 18 '15 07:08 gajus

@gajus Maybe, maybe not :-) I have to say that I've not found any need for it in any real life projects yet. I'll have a play around later and see if I can come up with any really compelling use cases.

ellbee avatar Aug 18 '15 07:08 ellbee

@gajus Here is the sort of situation where Immutable.is() as the equalsFn might possibly be helpful:


// state for reducer a:
Immutable.map({
  'list1': Immutable.List(),
  'list2': Immutable.List(),
  'keyword': ''
});

// selectors
const list1$ = state => state.a.get('list1');
const list2$ = state => state.a.get('list2');
const keyword$ = state => state.a.get('keyword');

const filteredList2$ = createSelector(
  [list2$, keyword$],
  (list2, keyword) => {
    return list2.filter(x => x.indexOf(keyword) !== -1);
  }
);

const createImmutableSelector = createSelectorCreator(Immutable.is);

const somethingExpensive$ = createImmutableSelector(
  [list1$, filteredList2$],
  (list1, filteredList2) => {
    return //expensive computation
  }
);

somethingExpensive$ with === as the equalsFn would re-run the expensive computation every time someone changed the keyword, even if that change did not cause any changes to the underlying data in filteredList$.

I'm not saying that this is the best approach, just that === will break memoization here.

@bunkat

I actually can't imagine a scenario where a reducer would systematically be returning a strictly equivalent update as new state. That would mean that changes are happening outside of actions which shouldn't be the case, otherwise you would always know when running the map, filter, reduce would be necessary.

Something I have done which is kind of like this was a background task, running on a timer, which filtered stale items from a list.

ellbee avatar Aug 18 '15 12:08 ellbee

@ellbee I am still not seeing it.

import Immutable from 'immutable';
import {
    createSelector,
    createSelectorCreator
} from 'reselect';

let state,
    list1Selector,
    list2Selector,
    keywordSelector,
    filteredList2Selector,
    somethingExpensiveSelector,
    createImmutableSelector;

// state for reducer a:
state = Immutable.Map({
    list1: Immutable.List(),
    list2: Immutable.List(),
    keyword: ''
});

list1Selector = state => state.get('list1');
list2Selector = state => state.get('list2');
keywordSelector = state => state.get('keyword');

filteredList2Selector = createSelector(
    [
        list2Selector,
        keywordSelector
    ],
    (list2, keyword) => {
        console.log('Generating filteredList2Selector...');
        return list2
            .filter(x => {
                return x.indexOf(keyword) !== -1;
            });
    }
);

createImmutableSelector = createSelectorCreator(Immutable.is);

somethingExpensiveSelector = createImmutableSelector(
    [
        list1Selector,
        filteredList2Selector
    ],
    (list1, filteredList2) => {
        console.log('Generating somethingExpensiveSelector...');

        return Math.random();
    }
);

console.log('filteredList2Selector(state)', filteredList2Selector(state));
console.log('filteredList2Selector(state)', filteredList2Selector(state));

console.log('filteredList2Selector(state)', somethingExpensiveSelector(state));
console.log('filteredList2Selector(state)', somethingExpensiveSelector(state));

If you run this in node, you will get:

Generating filteredList2Selector...
filteredList2Selector(state) List []
filteredList2Selector(state) List []
Generating somethingExpensiveSelector...
filteredList2Selector(state) 0.29932390339672565
filteredList2Selector(state) 0.29932390339672565

You can run this code using babel-node CLI tool.

gajus avatar Aug 18 '15 14:08 gajus

@gajus you need to modify keyword property of state in order to see the effect @ellbee described. In this case somethingExpensiveSelector will always be recalculated even if List returned by the filteredList2Selector contains the same items inside. That is because filteredList2Selector always returns new instance of List if recalculated. So just try to add one more line to your example:

console.log('filteredList2Selector(state)', filteredList2Selector(state));
console.log('filteredList2Selector(state)', filteredList2Selector(state));

console.log('filteredList2Selector(state)', somethingExpensiveSelector(state));

state.set('keyword', 'not empty string');

console.log('filteredList2Selector(state)', somethingExpensiveSelector(state));

vovacodes avatar Aug 18 '15 14:08 vovacodes