Mutations and query invalidation in TanStack Query
Queries read server state; mutations change it. After a write, invalidating the matching query key makes TanStack Query fetch the fresh list.
How it works
- Read the list. A
useQuerycall with key['todos']loads the list from a fake in-memory API.isFetchingis shown so you can see when the list reloads. [1] - Write with useMutation.
useMutationwrapssaveTodo. CallingaddTodo.mutate(text)runs it, andaddTodo.statusmoves fromidletopendingtosuccess. [1] - Refresh the cache. In
onSuccessthe example callsinvalidateQueries({ queryKey: ['todos'] }), which refetches the list so the new todo appears. [1]
Run and edit it
It runs in your browser, in a sandboxed frame that cannot see this site; the packages load from esm.sh only after you press Run.
import { useState } from 'react'
import { QueryClient, QueryClientProvider, useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
const queryClient = new QueryClient()
const db = [{ id: 1, text: 'Write docs' }, { id: 2, text: 'Ship release' }]
const wait = (ms) => new Promise((r) => setTimeout(r, ms))
// Fake server functions
async function getTodos() { await wait(500); return [...db] }
async function saveTodo(text) {
await wait(700)
const todo = { id: Date.now(), text }
db.push(todo)
return todo
}
function Todos() {
const client = useQueryClient()
const [text, setText] = useState('Review pull request')
const todos = useQuery({ queryKey: ['todos'], queryFn: getTodos })
const addTodo = useMutation({
mutationFn: saveTodo,
onSuccess: () => client.invalidateQueries({ queryKey: ['todos'] }),
})
return (
<div style={{ background: '#f8fafc', color: '#0f172a', borderRadius: 12, padding: 18, width: 440, fontSize: 14 }}>
<h3 style={{ margin: '0 0 10px' }}>Todos</h3>
<form onSubmit={(e) => { e.preventDefault(); if (text) addTodo.mutate(text) }} style={{ display: 'flex', gap: 8 }}>
<input value={text} onChange={(e) => setText(e.target.value)} style={{ flex: 1, padding: 6 }} />
<button disabled={addTodo.isPending}>{addTodo.isPending ? 'Saving…' : 'Add'}</button>
</form>
<div style={{ fontSize: 12, color: '#64748b', margin: '8px 0' }}>
mutation: <b>{addTodo.status}</b> · list fetching: <b>{String(todos.isFetching)}</b>
</div>
{todos.status === 'pending' ? <p>Loading…</p> : (
<ul style={{ margin: 0, paddingLeft: 18 }}>
{todos.data.map((t) => <li key={t.id}>{t.text}</li>)}
</ul>
)}
</div>
)
}
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<div style={{ minHeight: '100vh', display: 'grid', placeItems: 'center', background: '#111', fontFamily: 'system-ui, sans-serif' }}><Todos /></div>
</QueryClientProvider>
)
}
Type a todo and press Add: the mutation status turns pending, then the list refetches and shows the new item. Code written by AgentGid [1].
Type a todo and press Add: the mutation status turns pending, then the list refetches and shows the new item. Code written by AgentGid [1].Checked Oct 12, 2026: it starts without errors in Chromium with @tanstack/react-query 5.104.2, react 19.3.0, react-dom 19.3.0. Needs WebGL.
More TanStack Query examples
Fetching data with useQuery in TanStack Query Optimistic updates with rollback in TanStack Query Paginated queries in TanStack Query Dependent queries with enabled in TanStack Query
Sources
Explanations written by AgentGid from the official docs; the numbers in brackets point here. The code marked "written by AgentGid" is ours and free to copy.