-
Hi, I do remember the document used to describe how to use selectors in components to improve performance: // selectors don't rely on states or props
const selector = (state) => state.name
function App() {
const name = useStore(selector);
// ...
} or // selectors do rely on states or props
function App({id}) {
const selector = useCallback((state) => {
return state[id]
}, [id]);
const state = useStore(selector);
// ...
} now those cannot be found in the document. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 8 replies
-
Thanks for opening a discussion. In the past, we recommended the use of stable selectors in v3, because we were targeting v4 with useMutableSource at that point. After that, React deprecated experimental useMutableSource and provides useSyncExternalStore.
Now, zustand v4 is based on useSyncExternalStore, so stable selectors are not necessary. But if you have a stable selector, you can expect the performance is a little more improved. In summary: inline selectors are just fine and recommendedconst Component = () => {
const slice = useStore((state) => state.slice);
// ... useCallback for lightweight selectors is an extra overhead, and not recommendedconst Component = () => {
const slice = useStore(useCallback((state) => state.slice, [])); // ❌
// ... Having stable selectors can improve performance, but not very noticeableconst selector = (state) => state.slice; // ✅
const Component = () => {
const slice = useStore(selector);
// ... |
Beta Was this translation helpful? Give feedback.
Thanks for opening a discussion.
In the past, we recommended the use of stable selectors in v3, because we were targeting v4 with useMutableSource at that point.
After that, React deprecated experimental useMutableSource and provides useSyncExternalStore.
For more context:
Now, zustand v4 is based on useSyncExternalStore, so stable selectors are not necessary. But if you have a stable selector, you can expect the performance is a little more improved.
In summary:
inline selectors are just fine and recommended
u…