DEV Community

Cover image for Something to consider when sharing state with Zustand
Murat Can Yüksel
Murat Can Yüksel

Posted on

Something to consider when sharing state with Zustand

I've been using #zustand as store for my latest #react #typescript project and I want to share with you something that cost me some serious time and headache so that you won't fall into the same pith.

Say that you have the following store saved in zustand:



interface TransactionHashState {

  transactionHash: string;

  getTransactionHash: (transactionHash: string) => void;

}


export const useTransactionHashStore = create<TransactionHashState>()(

  (set) => ({

    transactionHash: "",

    getTransactionHash: (transactionHash) =>

      set(() => ({ transactionHash: transactionHash })),

  })

);

Enter fullscreen mode Exit fullscreen mode

In your components, there are two ways of calling its value:

The first way, that is const { getTransactionHash } = useTransactionHashStore.getState(); will work fine in most cases, but it will only take a snapshot of the state so when you make a change, it won't update in real time. I repeat, it won't update in real time.

If you want it to update immediately, you should call it like const { getTransactionHash } = useTransactionHashStore() (without the getState method), and all will be fine.

reactdeveloper #reactdevelopment #webdeveloper #webdevelopers #webdevelopment

Top comments (0)