Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zustand fetch with API call useEffect best practice

When fetching state from an API with Zustand in a useEffect function what is the best practice for doing that? Right now I am using it very simply:

export interface ModeState{
  modes: Mode[];
  fetchModes: () => void;
}

export const useModeStore = create<ModeState>((set) => ({
  modes: [],
  fetchModes: async () => {
    const modes: AcquisitionMode[] = await API.get(`/acquisition-modes`);
    await set({ modes });
  },
}));

In component render function:

  const modeStore = useModeStore()
  const modes = modeStore.modes
  
  useEffect(() => {
    modeStore.fetchModes()
  }, [])

However the documentation seems to imply there are multiple ways this could be written to be more efficient in terms of performance, especially if my store grows more complex with more values and fetch functions. Is it best practice to make one store per API call? Use slices to get just the part of the store you need in each component? Should I be using the store differently in useEffect? I can't find a clear example online of how you should use the store in useEffect. The subscribe documentation does not seem to apply to the use case where you are using the store to fetch values with an async function.

like image 727
CorayThan Avatar asked Nov 17 '25 10:11

CorayThan


1 Answers

I have used zustand in a similar fashion in the past. I would often have a sync method on the store which I call in a useEffect and pass to it any state that is available to the component and not the store. Another possibility could be to let a library optimized for fetching get the data and make it available to the store once fetched.

What the documentation refers to with regard to performance is that you can indeed select parts of your store with a provided selector. In these cases a rerender will only happen when

  • the previous and current selected value are different or
  • a custom provided equality function states that previous and current values are different.

If you want to get into more detail with regard to performance I can recommend this this article here (disclaimer, I wrote it)

Even so, those performance considerations do not influence so much how you would trigger a fetch from, say, a useEffect hook.

like image 102
flq Avatar answered Nov 19 '25 23:11

flq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!