Reset and isolate query caches in tests
Prefetch without treating the cache as authority
Prefetching can warm a cache before a component needs it. A route loader and a component can use a common key and query function so their reads refer to the same data. The example uses the established v5 prefetchQuery interface; the current documentation redirects some pages and flags older prefetch methods for future replacement, so lock a compatible v5 release and verify the installed API before migrating. A server-side loader may need a throwing read rather than best-effort prefetch. Router loading state and server cache ownership are separate decisions.
import React, { useState } from 'react';import { QueryClient, QueryClientProvider, useQuery, useInfiniteQuery, useQueries, useMutation, useQueryClient, keepPreviousData, dehydrate, HydrationBoundary } from '@tanstack/react-query';
function Panel() { const client=useQueryClient(); const [open,setOpen]=useState(false); const options={queryKey:['public-maps'],queryFn:async()=>['Atlas','Beacon'],staleTime:60000}; return <section><button onFocus={()=>client.prefetchQuery(options)} onClick={()=>setOpen(true)}>Open catalogue</button>{open && <Catalogue options={options}/>}</section>;}function Catalogue({options}) {const q=useQuery(options);return <p>{q.isError?'Unavailable':q.data?.join(', ') ?? 'Loading'}</p>;}export default function App() { const [client] = useState(() => new QueryClient({defaultOptions:{queries:{retry:false,refetchOnWindowFocus:false},mutations:{retry:false}}})); return <QueryClientProvider client={client}><Panel /></QueryClientProvider>;}Keyboard focus can start the read before activation, but the component still owns loading and error presentation. A warm fresh cache may avoid a new fetch. Prefetching is optional and may waste work; do not prefetch private account data merely because a link is visible. A route loader must use the right client lifetime, key and error semantics.
Transfer only approved cache data
import React, { useState } from 'react';import { QueryClient, QueryClientProvider, useQuery, useInfiniteQuery, useQueries, useMutation, useQueryClient, keepPreviousData, dehydrate, HydrationBoundary } from '@tanstack/react-query';function createSnapshot() { const source=new QueryClient(); source.setQueryData(['public-maps'],['Atlas']); source.setQueryData(['private-maps','demo'],['Internal draft']); const state=dehydrate(source,{shouldDehydrateQuery:q=>q.state.status==='success' && q.queryKey[0]==='public-maps',shouldDehydrateMutation:()=>false}); source.clear(); return state;}function Catalogue(){const q=useQuery({queryKey:['public-maps'],queryFn:async()=>['Atlas'],staleTime:60000});return <p>{q.data?.join(', ') ?? 'Loading'}</p>;}export default function App(){const [client]=useState(()=>new QueryClient()); const [snapshot]=useState(createSnapshot);return <QueryClientProvider client={client}><HydrationBoundary state={snapshot}><Catalogue/></HydrationBoundary></QueryClientProvider>;}Atlas is the expected public result. This illustrates transfer in one browser process, not SSR. In SSR allocate a server QueryClient per request; never share a mutable authenticated cache across users. Use a reviewed framework serialization mechanism that prevents script injection and only send data the recipient may see. A cache snapshot can contain private payloads, keys and metadata, not just visible text. Persistence adds another boundary: allowlist public data, set expiry and schema version, remove stored data on sign-out, and align retention with restore policy. Offline cached content may be stale; pending mutations need explicit replay and conflict policy. No actual persistence or server rendering is performed here.
Make test isolation an explicit boundary
import React, { useState } from 'react';import { QueryClient, QueryClientProvider, useQuery, useInfiniteQuery, useQueries, useMutation, useQueryClient, keepPreviousData, dehydrate, HydrationBoundary } from '@tanstack/react-query';function newTestClient(){return new QueryClient({defaultOptions:{queries:{retry:false,refetchOnWindowFocus:false},mutations:{retry:false}}});}function scenario(){const a=newTestClient(),b=newTestClient();a.setQueryData(['shelf','demo'],['Atlas']);const isolated=b.getQueryData(['shelf','demo'])===undefined;a.clear();b.clear();return isolated;}export default function App(){const [result]=useState(scenario);return <p>{result?'Clients isolated':'Unexpected shared data'}</p>;}Expected text: Clients isolated. This is a staged demonstration, not an executed library test. In an actual component test use a new client per test, controlled promises or fake timers, unmount the component and clear the client. Verify error, next page, cancellation, optimistic failure and session isolation by observable behavior. With Suspense integration, use the dedicated v5 useSuspenseQuery family and provide both a Suspense boundary for waiting and an error boundary for errors without usable data; stale data can still render on background failure. Do not assume ordinary enabled or placeholder options apply to dedicated Suspense Hooks. Framework and persistence integration, exact package versions and browser tests remain separate gates.
Practice
Plan two isolated tests where one client caches Atlas and another starts empty. Add a public-only hydration check, a failed request with retry disabled, and a delayed append that cannot trigger overlapping reads. Record which assertions require real QueryClient and browser execution.