Skip to content Skip to sidebar Skip to footer

Memoize Reselect Selector Output Based On A Single Input Selector Instead Of All

I have a Reselect selector that maps an array of chosen ids into objects from a normalized store. const activeObjectsSelector = createSelector( state => state.activeIds, sta

Solution 1:

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' },
  },
};
constselectActiveIds = (state) => state.activeIds;
constselectObjects = (state) => state.objects;
constcreateMemoizedArray = () => {
  const memArray = defaultMemoize((...array) => array);
  return(array) => memArray.apply(null, array);
};
constcreateSelectAcitiveObjects = () => {
  const memoizedArray = createMemoizedArray();
  returncreateSelector(
    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);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/reselect/4.0.0/reselect.min.js"></script><divid="root"></div>

Post a Comment for "Memoize Reselect Selector Output Based On A Single Input Selector Instead Of All"