Do I need to add zustand store to useEffect dependency array?

Viewed 20

I have a zustand store, like this

import create from 'zustand';

export const useNotificationStore = create((set) => ({
  notifications: [],
  addMessage: (payload) =>
    set((state) => ({
      notifications: [
        ...state.notifications,
        { ...payload },
      ],
    }))
}));

When using this store in React component, do I need to add this store to dependency list? For example

function Notify() {
  const notify = useNotificationStore();
  
  useEffect(() => {
    // do something async
    notify.addMessage({ ... })
  }, [dependency1]) // do I need to add notify here?

  return <div />
}

For redux, there was no need to add dispatch to dependency list. Is it true for zustand?

2 Answers

Technically yes – there's nothing stopping you from doing set({addMessage: ...}), and so notify.addMessage would change.

Practically: probably not.

For redux, there was no need to add dispatch to dependency list

Well, even though it is technically not needed to add dispatch to dependency lists in Redux, it is still a much better practice to include it anyway rather than ignoring/suppressing ESLint's warnings (or not using ESLint at all). So I'd suggest to always follow what the ESLint rule says. If it ends up never changing, then it doesn't hurt.

Related