Mutate data and invalidate related queries
Send writes through mutations
A query reads server-owned data; a mutation represents an operation that changes it. useMutation provides mutate (callback-driven) and mutateAsync (promise-returning), status, errors and pending state. Unlike a query, a mutation is triggered deliberately, such as by a button. This chapter uses an isolated in-memory service with a single record; it is not a real reservation system. In a real API enforce authorization, validate input, and account for duplicate submissions and conflicting writes.
import React, { useState } from 'react';import { QueryClient, QueryClientProvider, useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
function Panel() { const client=useQueryClient(); const [store]=useState(()=>({loaned:false})); const key=['loan','north','n1']; const query=useQuery({queryKey:key,queryFn:async()=>({...store})}); const mutation=useMutation({mutationFn:async()=>{store.loaned=true;return {...store};},onSuccess:()=>client.invalidateQueries({queryKey:key,exact:true})}); return <section><p>{query.data ? (query.data.loaned?'On loan':'Available') : 'Reading…'}</p> {query.isError&&<p role="alert">Read failed.</p>}{mutation.isError&&<p role="alert">Save failed.</p>} <button type="button" disabled={!query.data || query.data.loaned || mutation.isPending} onClick={()=>mutation.mutate()}>Borrow tripod</button> <p role="status">{mutation.isPending?'Saving…':''}</p></section>;}export default function App() { const [client] = useState(() => new QueryClient({defaultOptions:{queries:{retry:false,refetchOnWindowFocus:false}}})); return <QueryClientProvider client={client}><Panel /></QueryClientProvider>;}Initially Available; after borrowing and successful refresh, On loan. Invalidating marks matching queries stale and normally refetches active matches; returning the invalidation promise from onSuccess keeps this mutation pending until that work finishes. Invalidation does not directly edit the cached object and does not guarantee a successful refresh. A mutation is not automatically safe to retry; a timeout could occur after the server committed the write. Use idempotency and conflict handling where needed.
Preview a change and restore it on failure
import React, { useState } from 'react';import { QueryClient, QueryClientProvider, useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
function withLoan(row, loaned) { return {...row,loaned}; }async function saveLoan(store, loaned, fail) { if (fail) throw new Error('Simulated rejection'); store.loaned=loaned; return {...store};}function Panel() { const client=useQueryClient(); const [store]=useState(()=>({id:'n1',loaned:false})); const [fail,setFail]=useState(false); const key=['loan','north','n1']; const query=useQuery({queryKey:key,queryFn:async()=>({...store})}); const mutation=useMutation({ mutationFn:({loaned,fail})=>saveLoan(store,loaned,fail),retry:false, onMutate:async({loaned})=>{ await client.cancelQueries({queryKey:key,exact:true}); const previous=client.getQueryData(key); if(previous !== undefined) client.setQueryData(key,withLoan(previous,loaned)); return {previous}; }, onError:(_error,_variables,rollback)=>{if(rollback?.previous !== undefined) client.setQueryData(key,rollback.previous);}, onSettled:()=>client.invalidateQueries({queryKey:key,exact:true}) }); return <section><label><input type="checkbox" checked={fail} onChange={e=>setFail(e.target.checked)} disabled={mutation.isPending}/> Simulate rejection</label> <p>{query.data?(query.data.loaned?'On loan':'Available'):'Reading…'}</p> {query.isError&&<p role="alert">Read failed.</p>} <button type="button" disabled={!query.data||mutation.isPending} onClick={()=>mutation.mutate({loaned:!query.data.loaned,fail})}>Change loan status</button> <p role="status">{mutation.isPending?'Saving tentative change…':''}</p>{mutation.isError&&<p role="alert">Save rejected; checking confirmed state.</p>}</section>;}export default function App() { const [client] = useState(() => new QueryClient({defaultOptions:{queries:{retry:false,refetchOnWindowFocus:false}}})); return <QueryClientProvider client={client}><Panel /></QueryClientProvider>;}The cache is updated before confirmation, so the interface may show a tentative loan status. A rejection restores the saved record and triggers a new read. Cancellation before the cache write reduces interference from a running query. The rollback value is the result returned by onMutate; the v5 callback receives it as its third argument (newer signatures have additional context arguments). This example deliberately allows only one writer at a time through the single pending-disabled button; the mock settles quickly, so the optimistic frame may not be visible. Overlapping mutations, other writers, failed refreshes and server conflicts need a stronger policy; restoring a whole snapshot can overwrite newer changes. Chapter 25 examines those problems.
Separate cache lifetimes at an account boundary
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({account}) { const query=useQuery({queryKey:loanKey(account,'all'),queryFn:({signal})=>readLoans(account,'all',signal)}); return <section><h2>{account} equipment</h2>{query.isPending?<p role="status">Loading…</p>:query.isError?<p role="alert">Read failed.</p>:<ul>{query.data.map(x=><li key={x.id}>{x.name}</li>)}</ul>}</section>;}function Session({account}) { const [client]=useState(()=>new QueryClient({defaultOptions:{queries:{retry:false}}})); return <QueryClientProvider client={client}><Panel account={account}/></QueryClientProvider>;}export default function App() { const [account,setAccount]=useState('north'); return <main><label>Fictional session <select value={account} onChange={e=>setAccount(e.target.value)}><option value="north">North</option><option value="south">South</option></select></label><Session key={account} account={account}/></main>;}Switching account remounts Session with its own client. The old client is no longer available to the new subtree; South should never display North equipment. This fixture has no external references, persistence, real identity or live mutation during the switch. In a real sign-out flow stop old-session work, clear sensitive cache and persistence as appropriate, and scope all server authorization independently. A new client is not a guarantee of immediate memory erasure. In tests create a new client per test and clean up its observers and pending work; do not let an earlier test warm a later test’s cache.
Practice
Try a successful loan change, then force rejection and confirm that the original server-owned value remains after reconciliation. Switch North to South and back in the session fixture. Write a test plan that checks no other account records appear, without assuming the absence of an intermediate render.