TanStackT
TanStack2y ago
11 replies
then-purple

Initializing/synching Zustand stores with React Query

I know that we typically do not want to sync React Query data to Zustand, because React Query already does a good job of managing server state. But I was wondering if there is anything wrong with using React Query data to initialize a Zustand store if we know that we need to change the data locally before saving it back to our database.

For example, I am building a bulk email tool that lets you select multiple recipients using a virtual table. An email draft may already have some recipients selected, so when the page loads I want to fetch the email and initialize a Zustand context + store using any existing contacts from the email. Once this is done, users can select/deselect contacts in the table, which Zustand manages, and if they hit Save then I use a React Query mutation to update the Email in the database.

The code looks similar to this:

const { data: email, isLoading, isError } = useQuery(emailQueries.detail(emailId))

if (isLoading) { // ... }
if (isError) { // ... }

<ContactsProvider initialContacts={email.contacts}>
  <ContactsTable />
</ContactsProvider>


I'm following @TkDodo 🔮 's Zustand context pattern (https://tkdodo.eu/blog/zustand-and-react-context) so the ContactsProvider only creates the store once. This all works great, but it does feel a little odd to me because prior to using Zustand, my typical workflow was to fetch from React Query, make some changes, mutate, invalidate, refetch, and update the UI. But with the code above I'm taking an initial snapshot of the data, and then never reading from it again.

There's enough complexity inside of the ContactsTable that it is helpful to move a lot of its state management into Zustand. I guess I'm wondering if other folks have used this approach before of snapshotting state into a Zustand store, or if I'm going off in the wrong direction.
Zustand stores a global and don't need React Context - but sometimes, it makes sense to combine them regardless.
Zustand and React Context
Was this page helpful?