Fetching everything
The simplest way, but you will import all the data (I don't know is it will affect the performance or not)
const App = () => {
const state = useStore()
return {
<>
<h1>{state.title}</h1>
<p>{state.paragraph}</p>
</>
}
}
Selecting multiple state slices
const title = useStore((state) => state.title)
const paragraph = useStore((state) => state.paragraph)
It detects changes with strict-equality (old === new) by default, this is efficient for atomic state picks.
const nuts = useStore((state) => state.nuts)
const honey = useStore((state) => state.honey)
If you want to construct a single object with multiple state-picks inside, similar to redux's mapStateToProps, you can tell zustand that you want the object to be diffed shallowly by passing the shallow equality function.
import shallow from 'zustand/shallow'
// Object pick, re-renders the component when either state.nuts or state.honey change
const { nuts, honey } = useStore(
(state) => ({ nuts: state.nuts, honey: state.honey }),
shallow
)
// Array pick, re-renders the component when either state.nuts or state.honey change
const [nuts, honey] = useStore((state) => [state.nuts, state.honey], shallow)
// Mapped picks, re-renders the component when state.treats changes in order, count or keys
const treats = useStore((state) => Object.keys(state.treats), shallow)
For more control over re-rendering, you may provide any custom equality function.
const treats = useStore(
(state) => state.treats,
(oldTreats, newTreats) => compare(oldTreats, newTreats)
)
src: https://github.com/pmndrs/zustand#recipes