Ok to return an array from a selector function? #97
-
I'm not 100% clear on how immer/selector functions work under the hood. The docs say it's ok to return multiple substates via a map, but is it ok to select an array? For example: const ids = [...];
const res = store.useState((s) => {
return ids.map(id => s.myStuff[id]);
}, ids); Will this selector do what I expect? (i.e. fire when when the corresponding objects stored in Also, will the hook fire on updates to the map, or will it also fire when fields in objects inside the map are updated? It's unclear from the docs how this works and I want to make sure. I think another way to ask this question is whether the comparisons are deep or shallow. Thanks for making an awesome library! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @coffeemug ,
Yep- that should all work fine! It does do a deep-equal comparison on any value returned from the selector passed to How I would usually do something like this though- to improve performance slightly- is I would map over the But I can't know exactly what you're trying to do- but generally, selecting more specific state as opposed to large chunks is going to be a win. |
Beta Was this translation helpful? Give feedback.
Hi @coffeemug ,
Yep- that should all work fine! It does do a deep-equal comparison on any value returned from the selector passed to
useState()
.How I would usually do something like this though- to improve performance slightly- is I would map over the
ids
and return individual components which take anid
and then pick out the item they need inuseState(s => s.myStuff[id])
- this way, only the components with items which actually change inside your store get re-rendered.But I can't know exactly what you're trying to do- but generally, selecting more specific state as …