DEV Community

Discussion on: Using Zustand with React JS! 🚀

Collapse
 
stianhave profile image
Stian HÃ¥ve

isnt this a better way to get the properties from the store?

const {amount, updateAmount} = useBookStore()
Enter fullscreen mode Exit fullscreen mode

instead of

const amount = useBookStore(state => state.amount)
const updateAmount = useBookStore(state => state.updateAmount)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mohajerimasoud profile image
Masoud Mohajeri

no
if any other changes occur in store other than amount and updateAmount , you will have unnecessary rerender .

Collapse
 
stianhave profile image
Stian HÃ¥ve

Oh wow, had no clue. Thanks for pointing that out!
I guess it would still work with smaller and specific stores though, but i'll keep it in mind.

Collapse
 
joshnwosu profile image
Joshua Nwosu

This isn't true.

Thread Thread
 
stianhave profile image
Stian HÃ¥ve

Can you elaborate?

Collapse
 
ccreusat profile image
Clément Creusat • Edited

Best ways to avoid unnecessary rerenders with zustand are :

Direct selectors:

const amount = useBookStore(state => state.amount)
const updateAmount = useBookStore(state => state.updateAmount)
Enter fullscreen mode Exit fullscreen mode

Object destructuring with shallow:

import { shallow } from "zustand/shallow";

const { amount } = useBookStore((state) => ({
    amount: state.amount,
  }), shallow);
Enter fullscreen mode Exit fullscreen mode

Since v4.x.x, you can also use the useShallow hook:

import { useShallow } from 'zustand/react/shallow'

const { amount } = useBookStore(
    useShallow((state) => ({ amount: state.amount })),
);
Enter fullscreen mode Exit fullscreen mode

Other ways are wrong (unless re-renders / performance is not a problem) :

const state = useBookStore(); 
Enter fullscreen mode Exit fullscreen mode
const { amount } = useBookStore();
Enter fullscreen mode Exit fullscreen mode
const { amount } = useBookStore((state) => ({
    amount: state.amount,
}});
Enter fullscreen mode Exit fullscreen mode