Aaron Parisi
Aaron Parisi

Reputation: 708

Why is react-query invalidation bleeding across tabs?

I have 2 instances of storybook running an application locally. I have 2 tabs open on localhost:6006 and localhost:6007, and I log in as a different user on each.

I do things in 1 tab that invalidates certain queries based on query key like ['some', 'keys'].

What's unexpected is that the corresponding queries in the other tab re-execute. Any thoughts on why this might happen?

Thanks!

Upvotes: 0

Views: 24

Answers (1)

  1. Disable or Adjust Cache Persistence If you’re using persistQueryClient, remove it or configure it to use a storage mechanism that isn’t shared between tabs (e.g., indexedDB with user-scoped keys).

Example of disabling persistence:

// Remove or comment out the persistence setup
// persistQueryClient({
//   queryClient,
//   persister: localStoragePersister,
// });
  1. Add User-Specific Identifiers to Query Keys Include the logged-in user’s ID in your query keys to ensure cache isolation between users:

    // Include userID in the query key const queryKey = ['some', 'keys', currentUserID]; useQuery(queryKey, ...);

  2. Verify React Query Configuration Ensure refetchOnWindowFocus isn’t causing unintended refetches (though this is less likely unless you’re switching tabs):

    const queryClient = new QueryClient({ defaultOptions: { queries: { refetchOnWindowFocus: false, // Disable if needed }, }, });

Testing the Fix Temporarily disable persistence to see if the cross-tab invalidation stops.

Check query keys in both tabs using React Query Devtools. They should differ based on the logged-in user.

By isolating the cache per user/tab or removing shared persistence, you’ll prevent unintended query invalidations across tabs.

Upvotes: 1

Related Questions