Choose query keys and freshness policy
Give each distinct result a distinct key
A query key identifies data inside one QueryClient. Use serializable arrays and include the variables that affect the response, such as a fictional account and category. This prevents a filtered result from being mistaken for another. Two observers of the same key on the same client may share cached data and in-flight work; different clients and different keys have separate cache entries. This is not a guarantee of one request across all tabs or all time.
import React, { useState } from 'react';import { QueryClient, QueryClientProvider, useQuery, useMutation, useQueryClient } from '@tanstack/react-query';function loanKey(account, category) { return ['loans', account, category];}async function readLoans(account, category, signal) { if (signal?.aborted) throw signal.reason; if (!['north','south'].includes(account)) throw new Error('Unknown account'); const rows = account === 'north' ? [{id:'n1',name:'Tripod',category:'photo',loaned:false},{id:'n2',name:'Microphone',category:'audio',loaned:false}] : [{id:'s1',name:'Recorder',category:'audio',loaned:false}]; return rows.filter(row => category === 'all' || row.category === category);}
function Panel() { const [account,setAccount] = useState('north'); const [category,setCategory] = useState('all'); const query = useQuery({queryKey:loanKey(account,category),queryFn:({signal})=>readLoans(account,category,signal)}); return <section><label>Account <select value={account} onChange={e=>setAccount(e.target.value)}><option value="north">North</option><option value="south">South</option></select></label> <label>Category <select value={category} onChange={e=>setCategory(e.target.value)}>{['all','photo','audio'].map(c=><option key={c}>{c}</option>)}</select></label> {query.isPending?<p role="status">Loading…</p>:query.isError?<p role="alert">Read failed.</p>:query.data.length===0?<p>No matching equipment.</p>:<ul>{query.data.map(x=><li key={x.id}>{x.name}</li>)}</ul>} </section>;}export default function App() { const [client] = useState(() => new QueryClient({defaultOptions:{queries:{retry:false,refetchOnWindowFocus:false}}})); return <QueryClientProvider client={client}><Panel /></QueryClientProvider>;}North / all returns Tripod and Microphone; South / photo returns an empty list. Returning to a previous key may reveal its cached result and trigger a refresh depending on policy. Array item order matters; object members in a key are deterministically hashed by the library, not compared by JavaScript array identity. Do not put credentials in keys. Account-specific keys prevent accidental display reuse in this fixture, but are not an authorization boundary.
Choose freshness separately from retention
import React, { useState } from 'react';import { QueryClient, QueryClientProvider, useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
function Panel() { const query=useQuery({queryKey:['loan-summary'],queryFn:async()=>({available:2}),staleTime:60_000,gcTime:300_000}); return <section><p>{query.data ? `Available: ${query.data.available}` : 'No result yet'}</p> <p>Freshness: {query.isStale?'stale':'fresh'}</p> <p role="status">{query.isFetching?'Refreshing…':''}</p> {query.isError && <p role="alert">Read failed.</p>} <button type="button" disabled={query.isFetching} onClick={()=>query.refetch()}>Refresh now</button></section>;}export default function App() { const [client] = useState(() => new QueryClient({defaultOptions:{queries:{retry:false,refetchOnWindowFocus:false}}})); return <QueryClientProvider client={client}><Panel /></QueryClientProvider>;}staleTime describes how long a result is considered fresh (here one minute); stale data is not deleted. gcTime is the retention period for an unused query (here five minutes), not the maximum age of displayed data. In v5 the default staleTime is zero and inactive client queries are normally collected after five minutes. Earlier documentation calls gcTime cacheTime. Stale queries may refetch on mounting, focus or reconnect under configured defaults; becoming stale does not itself schedule a periodic request. Explicit refetch can fetch fresh data. Observe behavior with a controlled clock, rather than waiting five minutes in a graded task.
Cancel cooperating reads
import React, { useState } from 'react';import { QueryClient, QueryClientProvider, useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
function delayValue(signal, value, ms) { return new Promise((resolve,reject)=>{ if (signal.aborted) {reject(signal.reason);return;} const abort=()=>{clearTimeout(timer);reject(signal.reason);}; const timer=setTimeout(()=>{signal.removeEventListener('abort',abort);resolve(value);},ms); signal.addEventListener('abort',abort,{once:true}); });}function Panel() { const client=useQueryClient(); const query=useQuery({queryKey:['delayed-loans'],queryFn:({signal})=>delayValue(signal,['Tripod'],800)}); return <section><p role="status">{query.fetchStatus==='fetching'?'Reading…':query.data?'Ready':'No active read'}</p> {query.data && <p>{query.data.join(', ')}</p>}{query.isError&&<p role="alert">Read failed.</p>} <button type="button" disabled={!query.isFetching} onClick={()=>client.cancelQueries({queryKey:['delayed-loans'],exact:true})}>Cancel</button> <button type="button" disabled={query.isFetching} onClick={()=>query.refetch()}>Read again</button></section>;}export default function App() { const [client] = useState(() => new QueryClient({defaultOptions:{queries:{retry:false,refetchOnWindowFocus:false}}})); return <QueryClientProvider client={client}><Panel /></QueryClientProvider>;}Cancellation notifies the supplied signal and allows the timer to stop. Query cancellation can restore the earlier query state; a cancelled initial read may have no result and be idle. If a query function ignores cancellation, ordinary unmounting can allow the promise to finish and populate the cache. Consuming the signal lets the library cancel cooperating reads. Client cancellation never guarantees that a remote write has been undone.
Practice
Create keys for North / audio and South / audio. Predict their results and describe what happens if account is omitted. Explain the effect of a one-minute staleTime and five-minute gcTime. Test cancellation before and after the timer completes.