0

Say I have animals in a redux store. It's a normalized object, the key is the id and the value is the object itself. Each animal has a key is_dog.

animals: {
    'id1': { location: 'foo', is_dog: true, name: 'Dog1' },
    'id2': { location: 'foo', is_dog: false, name: 'Cat1' },
    'id3': { location: 'foo', is_dog: false, name: 'Cat2' },
    'id4': { location: 'foo', is_dog: true, name: 'Dog2' },
}

I have a DogsList connected react component that looks at the store state and passes in an array of dogIds to the UI component. Calculation of dogIds is something like:

dogIds = _.chain(state.animals).filter('is_dog').map('id').value();

In the example above this would return ['id1', 'id4'].

However, let's assume I have thousands of animals, and each animal has other properties that change frequently, say currentLocation, lastFed, etc. I know that dogIds will only change if is_dog changes for any animal, but I'm not quite sure how to not do the filter and map calculations unnecessarily on every change to any animal. I tried using reselect but I don't think it really helps in this case.

I'm leaning towards storing dogIds in redux proper, and manually updating it only when relevant. Like when a new dog is added to animals, or if a cat changes to a dog (my analogy is falling apart here). But I feel like I'm doing something wrong by keeping computed properties in a redux store.

Drew Schuster
  • 2,521
  • 12
  • 15

1 Answers1

1

Perhaps you could look into using React's lifecycle methods like shouldComponentUpdate - here you could assess whether newDogIDs !== oldDogIDs and then only do stuff if they are different.

rorymorris89
  • 1,144
  • 7
  • 14
  • Thanks, that's good feedback. What I was trying to avoid is the actual `filter` calculation, but the more I think about it the more it seems like that won't be too expensive unless I have millions of animals. – Drew Schuster Mar 24 '17 at 23:29
  • Thinking further, I think I may've misunderstood your question. From what it seems, you'll have to perform that calculation every time your list of animals updates, either way - otherwise you'll never know if a dog has became a cat, and so on. – rorymorris89 Mar 24 '17 at 23:30
  • I suppose if you are handling the actions for 1) adding/removing animals and 2) changing an animals type (from dog to cat), then you should know when you need to recalculate `dogsList` (if those actions haven't happened, there's no need) – rorymorris89 Mar 24 '17 at 23:34