Memoize Reselect selector output based on a single input selector instead of all

Viewed 195

I have a Reselect selector that maps an array of chosen ids into objects from a normalized store.

const activeObjectsSelector = createSelector(
  state => state.activeIds,
  state => state.objects.byId,
  (activeIds, objectsById) => activeIds.map(id => objectsById[id])
)

The problem is that it busts the cache and re-runs anytime new objects are added to the normalized store, because the value of state.objects.byId changes. The only change I care about busting the cache is the value of state.activeIds. Is this possible?

1 Answers

You can use defaultMemoize of reselect for this to memoize the result of the map by passing it to a memoized function that will take the items of the array as arguments:

const { createSelector, defaultMemoize } = Reselect;
const state = {
  activeIds: [1, 2],
  objects: {
    1: { name: 'one' },
    2: { name: 'two' },
    3: { name: 'three' },
  },
};
const selectActiveIds = (state) => state.activeIds;
const selectObjects = (state) => state.objects;
const createMemoizedArray = () => {
  const memArray = defaultMemoize((...array) => array);
  return (array) => memArray.apply(null, array);
};
const createSelectAcitiveObjects = () => {
  const memoizedArray = createMemoizedArray();
  return createSelector(
    selectActiveIds,
    selectObjects,
    (ids, objects) =>
      memoizedArray(ids.map((id) => objects[id]))
  );
};
const selectAcitiveObjects = createSelectAcitiveObjects();
const one = selectAcitiveObjects(state);
console.log('one is:',one);
const two = selectAcitiveObjects(state);
console.log('one is two', two === one);
const newState = { ...state, activeIds: [1, 2, 3] };
const three = selectAcitiveObjects(newState);
console.log('three is two', three === two);
<script src="https://cdnjs.cloudflare.com/ajax/libs/reselect/4.0.0/reselect.min.js"></script>


<div id="root"></div>

Related