I've been working with Ngrx for a while now, and I've encountered a little issue.
I have an object in my store, which holds pairings of recipeId-thumbnailURL:
recipeIdThumbnailPairs: { [recipeId: string]: string }
The thumbnail is stored this way, because it's not actually recipes thumbnail but rather the "newest photo in recipes photos gallery".
problem appears, when I add a new recipe to the base. I'd like to add a new pair to the existing object, but obviously, since we work with Redux pattern, I have to clone the entire object. This triggers change on all selectors which access thumbnail for each specific recipe - this causes all thumbnails to re-render, because they think they were changed!
Does anyone have any idea how to work around this behaviour?
Ok so the re-rendering can be caused by a few things.
If you are rendering lists, it always makes sense to use the trackBy
function so that updating a single item will not cause the whole list to rerender:
https://netbasal.com/angular-2-improve-performance-with-trackby-cc147b5104e5
Then, to prevent each thumbnail from rerendering you can also create a component which has a string as @Input
and give that component ChangeDetectionStratagey.OnPush
. That will make it so that the component only re-renders if an input changes or it receives an event.
Is storing mutable things as key-value pairs in object a bad thing?
No, not necessearily, but this can make it a lot easier: https://ngrx.io/guide/entity
Wouldn't the same happen if it was a simple array?
Yes, I believe so. In fact, since I guess you are iterating somewhere with ngFor
that makes it an array anyways in the eyes of the renderer.