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:

    Cons:

    Scenario b (Using get Function):

    Pros:

    Cons:

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