DEV Community

Discussion on: Using Zustand with React JS! 🚀

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