Search code examples
reactjszustand

Is using "state" rather than "get" in a store different and/or better?


Lets say I have the following store:

// Scenario a.
export const useStoreWithState = create<ContextType>()((set) => ({
  A: "A",
  B: "B",
  setA: () => set((state) => ({ A: state.A + "A" })),
  setB: () => set((state) => ({ B: state.B + "B" })),
}));

According to the documentation, we can also write it in a more concise way, like this:

// Scenario b.
export const useStoreWithGet = create<ContextType>()((set, get) => ({
  A: "A",
  B: "B",
  setA: () => set({ A: get().A + "A" }),
  setB: () => set({ B: get().B + "B" }),
}));

Are those 2 syntax completely equivalent?
If yes, then is there a good practice, or pros/cons using one or an other?
I prefer the second one, because it is a bit shorter, but maybe it is less readable? But I have the feeling doing something wrong using this get inside the set function, as usually, the set function uses the previous state with a parameter, like in the scenario a.


Solution

  • Pros and Cons:

    Scenario a (Using Callback Function):

    Pros:

    • More explicit about how the state is updated, especially in complex scenarios.
    • Can be easier to understand for developers new to Zustand or functional programming concepts.

    Cons:

    • Slightly longer syntax may be seen as less concise.

    Scenario b (Using get Function):

    Pros:

    • Shorter and more concise syntax.
    • May be preferred by developers who are comfortable with the get function and find it more readable.

    Cons:

    • May be less explicit about the state update mechanism, potentially leading to confusion in more complex scenarios.

    Which scenario to use or is a good practice comes down to personal preference and team conventions.