Search code examples
reactjsreact-statereact-state-managementzustand

Should I Create Functions Inside The Component or Put Them In The State (Zustand)


Hope you're doing fine!

Here's my question. Where should I store functions? In a Component, or directly in the store?

Suppose I have a component called RevisionList. One RevisionList renders multiple revisions (Revision component). You can select each revision by clicking on it. So each revision needs to make use of the method called setCurRev.

So, I have two options here. Either define it inside the Revision component:

  const curRevId = useStore(s => s.curRevId);
  const hideRefRevFinalVer = useStore(s => s.hideRefRevFinalVer)
  const app = useStore(s => s.app);

  const setCurRev = (id: RevId) => {
    if (id === curRevId) return;
    hideRefRevFinalVer();
    app.setRevisionById(id);
  };
  

Or I could define it directly in the state slice:

const setCurRev = (id: RevId) => {
    if (id === get().curRev?.id) return;

    get().hideRefRevFinalVer();
    get().app.setRevisionById(id);
  };

And then use it in the Revision component like this:

const setCurRev = useStore(s => s.setCurRev)

Which is a better option in your opinion? I guess the second variant may cause fewer rerenders, so I should go with it. Thanks!


Solution

  • IMO, set and get functions should be defined in the state slice. This way you can reuse them in many components.

    Here is an example from Zustand's Github repo:

    import omit from "lodash-es/omit"
    
    const useStore = create(set => ({
      salmon: 1,
      tuna: 2,
      deleteEverything: () => set({ }, true), // clears the entire store, actions included
      deleteTuna: () => set(state => omit(state, ['tuna']), true)
    }))