DEV Community

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

Posted on

2

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

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (1)

Collapse
 
ritwan_alrashit_f55372232 profile image
Ritwan Alrashit

I have this issue now, and the reason I am using getState() is that I am not in a React component. I am using it in a normal function, which I can't call it in a hook...

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay