-
Imagine you have a store as such: // store.js
const useStore = create(set => ({
bears: [{ id: 1, attitude: 'angry'}, { id: 2, attitude: 'playful'}]
})) and a component using that store: // component.js
function AngryBear() {
const bears = useStore(state => state.bears.filter(bear => bear.attitude === 'angry'))
return <h1>{bears.length} angry bears around here</h1>
} What would be the best way to memoize this selector to avoid unneeded work?
Thanks :) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 10 replies
-
https://github.com/pmndrs/zustand#memoizing-selectors Defining selectors outside component will be most preferable. In the future version (v4), this style will be more performant than inline selectors. If selectors depend on props, (In this context, I assume the selector function is lightweight.) |
Beta Was this translation helpful? Give feedback.
-
Did the documentation for #memoizing-selectors go missing or get deleted? It doesn't seem to exist anymore on the readme. |
Beta Was this translation helpful? Give feedback.
https://github.com/pmndrs/zustand#memoizing-selectors
Defining selectors outside component will be most preferable. In the future version (v4), this style will be more performant than inline selectors. If selectors depend on props,
useCallback
would be recommended. That said, it's rather unopinionated, so either way is fine.(In this context, I assume the selector function is lightweight.)