Design optimistic cache updates
Keep tentative UI separate from confirmed data
Optimism makes a change visible before the authority confirms it. Chapter 24 used a single-writer cache snapshot. Here a temporary display is often easier: when the mutation is pending, show the proposed name with a label. If the operation fails, remove the proposal, keep the confirmed result and explain the failure. A real request can succeed even when its response is lost, so retries of writes require a service-level idempotency or conflict contract.
import React, { useState } from 'react';import { QueryClient, QueryClientProvider, useQuery, useInfiniteQuery, useQueries, useMutation, useQueryClient, keepPreviousData, dehydrate, HydrationBoundary } from '@tanstack/react-query';
function Panel() { const [confirmed,setConfirmed]=useState('Atlas'); const [reject,setReject]=useState(false); const m=useMutation({mutationFn:async name=>{if(reject) throw new Error('Rejected'); return name;},onSuccess:setConfirmed}); return <section><p>Confirmed name: {confirmed}</p>{m.isPending && <p role="status">Proposed: {m.variables}</p>}{m.isError && <p role="alert">Rename rejected.</p>} <label><input type="checkbox" checked={reject} disabled={m.isPending} onChange={e=>setReject(e.target.checked)}/>Simulate rejection</label> <button disabled={m.isPending} onClick={()=>m.mutate('New atlas')}>Rename map</button> </section>;}export default function App() { const [client] = useState(() => new QueryClient({defaultOptions:{queries:{retry:false,refetchOnWindowFocus:false},mutations:{retry:false}}})); return <QueryClientProvider client={client}><Panel /></QueryClientProvider>;}This deliberately local demonstration keeps the last confirmed value in state rather than a server cache. On success New atlas becomes confirmed; on failure the previous name remains. Instant promises may hide the intermediate frame. With actual server queries, reconcile affected reads after the mutation; a temporary label is not a database transaction.
Use targeted cache changes for shared views
import React, { useState } from 'react';import { QueryClient, QueryClientProvider, useQuery, useInfiniteQuery, useQueries, useMutation, useQueryClient, keepPreviousData, dehydrate, HydrationBoundary } from '@tanstack/react-query';function renameRow(rows,id,name) { return rows.map(row => row.id === id ? {...row,name} : row);}function Panel() { const client=useQueryClient(); const [service]=useState(()=>({rows:[{id:'a',name:'Atlas'},{id:'b',name:'Beacon'}]})); const [reject,setReject]=useState(false); const queryKey=['shelves','demo','east']; const q=useQuery({queryKey,queryFn:async()=>service.rows.map(row=>({...row}))}); const m=useMutation({mutationFn:async()=>{if(reject)throw new Error('Rejected'); service.rows=renameRow(service.rows,'a','Updated atlas'); return service.rows[0];}, onMutate:async()=>{await client.cancelQueries({queryKey,exact:true}); const before=client.getQueryData(queryKey); client.setQueryData(queryKey,old=>old?renameRow(old,'a','Updated atlas'):undefined); return {before};}, onError:(_error,_variables,context)=>{if(context?.before!==undefined)client.setQueryData(queryKey,context.before);}, onSettled:()=>client.invalidateQueries({queryKey,exact:true})}); return <section><ul>{q.data?.map(row=><li key={row.id}>{row.name}</li>)}</ul>{q.isError && <p role="alert">Read failed.</p>}{m.isError && <p role="alert">Write rejected.</p>} <label><input type="checkbox" checked={reject} disabled={m.isPending} onChange={e=>setReject(e.target.checked)}/>Reject write</label> <button disabled={!q.data || q.isFetching || m.isPending} onClick={()=>m.mutate()}>Update Atlas</button></section>;}export default function App() { const [client] = useState(() => new QueryClient({defaultOptions:{queries:{retry:false,refetchOnWindowFocus:false},mutations:{retry:false}}})); return <QueryClientProvider client={client}><Panel /></QueryClientProvider>;}The service object is an isolated mutable mock, not React display state; only the query cache drives the visible records. The cache change copies the array and target row. A rejection restores the earlier collection, then a targeted refresh checks the service. This fixture permits one writer only. A whole-collection rollback could erase another writer’s later update; for concurrent work use a per-operation overlay, version checks, serialization where appropriate or conflict-aware reconciliation. Do not retry unknown-outcome writes blindly. If a record appears in multiple filtered lists, choose all genuinely affected keys; exact invalidation alone is not sufficient in that case.
Select a view without replacing source data
import React, { useState } from 'react';import { QueryClient, QueryClientProvider, useQuery, useInfiniteQuery, useQueries, useMutation, useQueryClient, keepPreviousData, dehydrate, HydrationBoundary } from '@tanstack/react-query';function shelfKey(account,shelf) { return ['shelves',account,shelf];}function Panel() { const options={queryKey:shelfKey('demo','east'),queryFn:async()=>[{id:'a',name:'Atlas'},{id:'b',name:'Beacon'}]}; const names=useQuery({...options,select:rows=>rows.map(row=>row.name)}); const count=useQuery({...options,select:rows=>rows.length}); return <section>{(names.isError || count.isError) && <p role="alert">Read failed.</p>}<p>Maps: {count.data ?? 'Waiting'}</p><ul>{names.data?.map(name=><li key={name}>{name}</li>)}</ul></section>;}export default function App() { const [client] = useState(() => new QueryClient({defaultOptions:{queries:{retry:false,refetchOnWindowFocus:false},mutations:{retry:false}}})); return <QueryClientProvider client={client}><Panel /></QueryClientProvider>;}The expected count is 2. select transforms what an observer receives; it does not rewrite the stored collection. Keep selectors pure. Names are unique in this small fixture only; real row keys should be stable IDs. Avoid using a shared query key for different server response shapes. Invalidation reconciles the underlying data and both observers can receive updated projections.
Practice
Trace an optimistic rename A, a second rename B, and a late failure of A. Explain why restoring A’s whole snapshot can remove B. Propose a per-operation display or service version check and distinguish it from actual tested concurrency.