Skip to content
Agents tracked: 440 Downloads (7d): 202M down 19.5% GitHub stars: 10.4M Releases (7d): 607 Agent status: 3 with issuesSince last limit reset: Claude 28d · Codex 0d Updated Oct 21, 2026

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.

All TanStack Query examples TanStack Query: usage and stats

Mutations and query invalidation in TanStack Query: screenshot of the example below running
The code below, running in Chromium on our server (Oct 12, 2026). Press Run to see it live and change it.

How it works

  1. Read the list. A useQuery call with key ['todos'] loads the list from a fake in-memory API. isFetching is shown so you can see when the list reloads. [1]
  2. Write with useMutation. useMutation wraps saveTodo. Calling addTodo.mutate(text) runs it, and addTodo.status moves from idle to pending to success. [1]
  3. Refresh the cache. In onSuccess the example calls invalidateQueries({ 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>
  )
}
Ctrl/⌘ + Enter runs

Free for signed-in members, with a daily limit. Describe the change in plain words; the new code runs only in your browser.

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

  1. TanStack Query website

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.

Building something with TanStack Query? Ask AgentGid →