Skip to content

Volume ITechnology

6.4.11 — TanStack Query: Changing Data, and Keeping the Cache Honest ​

A customer clicks the heart on a product to mark it as a favorite. Three things must happen. The change must reach the server. The product list on screen must show the filled heart. And the "My favorites" page, which shows the same products, must agree.

Page 6.4.10 taught reading. This page teaches writing: how to send a change to the server, and how to make every screen that shows that data tell the truth afterwards. This second job is where most bugs in real apps live.

1. useMutation: a query that waits to be told ​

A mutation is a change that you send to the server: create, update, delete. (The word comes from "mutate", to change.) It differs from a query in three ways.

QueryMutation
When it runsby itself, when the component appearsonly when you call mutate(...)
Cached under a keyyesno
Meant forreadingwriting

Here is a first one. The scenario is adding a product to the shop (an admin screen).

First, one more helper next to the getJson you already know. It sends data:

ts
// src/api/client.ts
export async function getJson<T>(url: string, signal?: AbortSignal): Promise<T> {
  const res = await fetch(url, { signal })
  if (!res.ok) throw new Error(`The server answered ${res.status}`)
  return (await res.json()) as T
}

export async function sendJson<T>(
  url: string,
  method: 'POST' | 'PUT' | 'PATCH' | 'DELETE',
  body?: unknown,
): Promise<T> {
  const res = await fetch(url, {
    method,
    headers: { 'Content-Type': 'application/json' },                               // (1)
    body: body === undefined ? undefined : JSON.stringify(body),                   // (2)
  })
  if (!res.ok) throw new Error(`The server answered ${res.status}`)
  return (await res.json()) as T
}
  1. This header tells the server that the body is JSON.
  2. JSON.stringify turns the object into text, which is what travels over the network.

Now the keys and the mutation:

ts
// src/api/products.ts
export type Product = { id: string; name: string; priceCents: number; favorite: boolean }

export const productKeys = {
  all: ['products'] as const,
  list: (filters: { category: string }) => [...productKeys.all, 'list', filters] as const,
  detail: (id: string) => [...productKeys.all, 'detail', id] as const,
}
tsx
// src/components/AddProductForm.tsx
import { useState } from 'react'
import type { FormEvent } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { sendJson } from '../api/client'
import { productKeys } from '../api/products'
import type { Product } from '../api/products'

type NewProduct = { name: string; priceCents: number }

export function AddProductForm() {
  const queryClient = useQueryClient()                                             // (1)
  const [name, setName] = useState('')

  const addProduct = useMutation({
    mutationFn: (newProduct: NewProduct) => sendJson<Product>('/api/products', 'POST', newProduct),   // (2)
    onSuccess: () => queryClient.invalidateQueries({ queryKey: productKeys.all }),                    // (3)
  })

  function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    addProduct.mutate({ name, priceCents: 1000 })                                  // (4)
    setName('')
  }

  return (
    <form onSubmit={handleSubmit}>
      <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Product name" />
      <button type="submit" disabled={addProduct.isPending}>                       {/* (5) */}
        {addProduct.isPending ? 'Saving…' : 'Add product'}
      </button>
      {addProduct.isError && <p role="alert">Could not save: {addProduct.error.message}</p>}
    </form>
  )
}
  1. useQueryClient() gives you the same client you put in the provider. You need it to talk to the cache.
  2. mutationFn does the work. It receives one argument, the variables you pass to mutate. If you need several values, pass one object.
  3. onSuccess runs after the server accepted the change. We tell the cache that all product data is now out of date. The next section explains this call.
  4. mutate(...) starts it. You may call it as many times as you like.
  5. A mutation has its own states, like a query: isPending (request running), isError, isSuccess, error, data. We disable the button while pending, so a double click cannot add the product twice.

2. Telling the cache it is out of date: invalidateQueries ​

After the product is added, the list on screen is wrong. It does not contain the new product, and it will not until it is fetched again. The cache has no way of knowing. You must tell it.

invalidateQueries does two things:

  1. It marks the matching cache entries as stale, even if their staleTime has not run out.
  2. It refetches right now every one of those that a component is currently showing. Entries nobody is showing are only marked. They will refetch the next time someone uses them.

The key you pass is a prefix. Everything whose key starts with it is affected. This is why we built the key factory in the last page with a shared root:

ts
queryClient.invalidateQueries({ queryKey: ['products'] })
// affects ['products', 'list', { category: 'kitchen' }]
//     and ['products', 'list', { category: 'garden' }]
//     and ['products', 'detail', 'p1']  ...everything that starts with 'products'

We tested it with a list and a detail query on screen. After a successful add, the invalidation made both refetch (the fetch counts went from 1 to 2 for each), and the list showed the new product. We also tested an entry that nobody was showing. It was marked as invalidated, and no request went out.

You can aim more narrowly. invalidateQueries({ queryKey: productKeys.detail('p1') }) hits only that one product. Choose the narrowest key that is still correct.

A detail that pays off: onSuccess here returns the promise from invalidateQueries. When you return a promise, the mutation stays in the isPending state until the refetch has finished. So the button stays disabled until the list really shows the new product, not just until the server said yes.

Other ways to keep the cache correct ​

Invalidating costs one extra request. Sometimes you already have the new data and can write it straight into the cache.

tsx
const updateName = useMutation({
  mutationFn: ({ id, name }: { id: string; name: string }) =>
    sendJson<Product>(`/api/products/${id}`, 'PATCH', { name }),
  onSuccess: (updated) => {
    queryClient.setQueryData(productKeys.detail(updated.id), updated)              // (1)
    queryClient.invalidateQueries({ queryKey: [...productKeys.all, 'list'] })      // (2)
  },
})
  1. setQueryData(key, newValue) writes a value into the cache. The detail page updates at once. The server's answer (updated) is the new truth, so we use it. Remember the rule from page 6.4.2: the value you write must be new, never the old object changed in place.
  2. We still invalidate the lists, because the changed name could affect their order or filters, and we cannot compute that ourselves.

A good rule: write directly when you know exactly what changed; invalidate when you do not.

3. mutate or mutateAsync? ​

Both start the mutation. They differ in what you get back.

tsx
addProduct.mutate(newProduct)                       // returns nothing
const created = await addProduct.mutateAsync(newProduct)   // returns a promise of the result

mutate is the normal choice. You react through the onSuccess and onError options, or through isError in the JSX. mutateAsync returns a promise, so you can await it, but then you must catch errors with try and catch, or you get an unhandled rejection.

One useful feature: you can pass callbacks to a single mutate call, for things that belong to this one use, like moving to another page:

tsx
addProduct.mutate(newProduct, {
  onSuccess: (created) => navigate(`/products/${created.id}`),
})

(navigate is from React Router, page 6.4.9.) The callbacks in useMutation itself run always, such as invalidation. The callbacks in mutate run for this call only, and not if the component has already left the screen.

4. Optimistic updates: change the screen first ​

With the code so far, clicking the heart does this: send the request, wait (maybe 300 ms), refetch the list (another 300 ms), and only then does the heart fill in. Over a slow connection it feels broken.

An optimistic update assumes the server will say yes. It updates the screen immediately, sends the request, and only if the server says no does it go back. Look at the sequence:

① Click Likeuser pressesthe button② Save the old valueprevious = count 1(kept for later)③ Update the screenshow count 2right now④ Ask the serverPOST /liketakes 300 ms⑤a Server says yeskeep count 2,then refetch to be sure⑤b Server says noput back count 1and show an errorFast feeling for the user. Honest result if something fails.
An optimistic update changes the screen first and asks the server afterwards. The saved earlier value is kept, so if the server says no, the screen can go back as if nothing happened.

The trick is step ②. Before changing anything, we save the old value. If the server refuses, we put it back. Here is the full version for the favorite heart:

tsx
// src/hooks/useToggleFavorite.ts
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { sendJson } from '../api/client'
import { productKeys } from '../api/products'
import type { Product } from '../api/products'

export function useToggleFavorite(category: string) {
  const queryClient = useQueryClient()
  const listKey = productKeys.list({ category })

  return useMutation({
    mutationFn: ({ id, favorite }: { id: string; favorite: boolean }) =>
      sendJson<Product>(`/api/products/${id}/favorite`, 'PUT', { favorite }),

    onMutate: async ({ id, favorite }) => {                                        // (1)
      await queryClient.cancelQueries({ queryKey: listKey })                       // (2)
      const previous = queryClient.getQueryData<Product[]>(listKey)                // (3)
      queryClient.setQueryData<Product[]>(listKey, (old) =>                        // (4)
        old?.map((p) => (p.id === id ? { ...p, favorite } : p)),
      )
      return { previous }                                                          // (5)
    },

    onError: (_error, _variables, context) => {                                    // (6)
      queryClient.setQueryData(listKey, context?.previous)
    },

    onSettled: () => queryClient.invalidateQueries({ queryKey: productKeys.all }), // (7)
  })
}
  1. onMutate runs before the request is sent. It receives the same variables as mutationFn.
  2. Cancel any refetch of this list that is in flight. If an old answer arrived after our change, it would overwrite the optimistic value and the heart would flicker back.
  3. Read the current list from the cache. This is our backup.
  4. Write the changed list into the cache. The product with this id gets a new object with the new favorite. All the others are the same objects as before. The screen updates at once.
  5. Whatever onMutate returns is handed to the later callbacks as context. We pass the backup along.
  6. onError runs if the server refused. We put the backup back. The heart returns to how it was.
  7. onSettled runs at the end, whether it worked or not. We refetch, so the cache matches the server's real state, no matter what happened.

We ran this sequence against a pretend server. When the server accepted, the count went up at once and stayed. When it refused, we saw, in order: onMutate, the screen showing the new value, then onError (rollback), then onSettled, and the screen was back to the old value.

Use it in a component, with a heart that changes immediately:

tsx
// src/components/FavoriteButton.tsx
import { useToggleFavorite } from '../hooks/useToggleFavorite'
import type { Product } from '../api/products'

export function FavoriteButton({ product, category }: { product: Product; category: string }) {
  const toggle = useToggleFavorite(category)

  return (
    <button
      aria-pressed={product.favorite}
      onClick={() => toggle.mutate({ id: product.id, favorite: !product.favorite })}
    >
      {product.favorite ? '♥' : '♡'}
    </button>
  )
}

product.favorite comes from the cache. Because onMutate already changed the cache, the heart flips before the server answers.

The simpler way, for one screen ​

Writing to the cache is powerful, but it is a lot of code. If only one place shows the change, there is a much shorter option. While the mutation is running, mutation.variables holds what you sent. You can draw that directly, with no cache changes at all:

tsx
// src/components/AddProductWithPreview.tsx
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { getJson, sendJson } from '../api/client'
import { productKeys } from '../api/products'
import type { Product } from '../api/products'

export function AddProductWithPreview() {
  const queryClient = useQueryClient()
  const list = useQuery({
    queryKey: productKeys.list({ category: 'all' }),
    queryFn: () => getJson<Product[]>('/api/products'),
  })
  const add = useMutation({
    mutationFn: (name: string) => sendJson<Product>('/api/products', 'POST', { name }),
    onSettled: () => queryClient.invalidateQueries({ queryKey: productKeys.all }),
  })

  return (
    <>
      <ul>
        {list.data?.map((p) => <li key={p.id}>{p.name}</li>)}
        {add.isPending && <li style={{ opacity: 0.5 }}>{add.variables}</li>}       {/* (1) */}
      </ul>
      <button onClick={() => add.mutate('New product')}>Add</button>
    </>
  )
}
  1. While the request is running, a faded extra row shows what we are adding. When the mutation settles, isPending becomes false, the faded row disappears, and the refetched list contains the real product. If it fails, the row simply vanishes. There is nothing to roll back, because we never touched the cache.

Choose by how many places show the data. One place: show variables. Many places: write to the cache in onMutate, and roll back in onError.

5. Getting data ready before it is needed ​

Two more cache tools make a shop feel fast.

Prefetch on hover. When the customer moves the mouse over a product link, there is a good chance they will click it. Start loading its detail page data right then, so it is already in the cache when they click.

tsx
// src/components/ProductLink.tsx
import { useQueryClient } from '@tanstack/react-query'
import { Link } from 'react-router'
import { getJson } from '../api/client'
import { productKeys } from '../api/products'
import type { Product } from '../api/products'

export function ProductLink({ id, name }: { id: string; name: string }) {
  const queryClient = useQueryClient()

  return (
    <Link
      to={`/products/${id}`}
      onMouseEnter={() =>
        queryClient.prefetchQuery({
          queryKey: productKeys.detail(id),
          queryFn: () => getJson<Product>(`/api/products/${id}`),
          staleTime: 30_000,                                                       // (1)
        })
      }
    >
      {name}
    </Link>
  )
}
  1. prefetchQuery only fetches if the entry is missing or stale. With a staleTime, hovering over the same link ten times sends one request.

Use the router and the cache together. React Router's loaders (page 6.4.9) run before the page draws, but they do not remember anything. TanStack Query remembers but does not know about routes. Joining them gives you both. The loader asks the cache with ensureQueryData, and the component reads with useQuery:

tsx
// src/pages/ProductPage.tsx
import { useQuery } from '@tanstack/react-query'
import type { QueryClient } from '@tanstack/react-query'
import { useParams } from 'react-router'
import type { LoaderFunctionArgs } from 'react-router'
import { getJson } from '../api/client'
import { productKeys } from '../api/products'
import type { Product } from '../api/products'

const productDetail = (id: string) => ({
  queryKey: productKeys.detail(id),
  queryFn: () => getJson<Product>(`/api/products/${id}`),
})

export const productLoader =
  (queryClient: QueryClient) =>                                                    // (1)
  ({ params }: LoaderFunctionArgs) =>
    queryClient.ensureQueryData({ ...productDetail(params.productId!), staleTime: 30_000 })   // (2)

export function ProductPage() {
  const { productId } = useParams()
  const { data: product } = useQuery(productDetail(productId!))                    // (3)
  if (!product) return null
  return <h1>{product.name}</h1>
}
  1. The loader needs the queryClient, which is not a global. So we make a function that takes it and returns the real loader. In router.tsx you write loader: productLoader(queryClient).
  2. ensureQueryData returns the cached value if it is there, and fetches it only if missing. We tested it: two calls and one prefetchQuery on fresh data made one request.
  3. The component reads the same key. Because the loader filled the cache before the page drew, the data is there on the first render, and later changes (a mutation's invalidation) update the page automatically. You get the "no loading flash" of a loader and the cache.

6. One place for all errors ​

Showing an error toast in every onError is repetitive. You can set one handler for the whole app, when you create the client:

tsx
import { MutationCache, QueryCache, QueryClient } from '@tanstack/react-query'

function showToast(message: string) {
  console.error(message)          // replace with your toast library
}

export const queryClient = new QueryClient({
  queryCache: new QueryCache({
    onError: (error, query) => {
      // only tell the user when a query that already had data fails to refresh
      if (query.state.data !== undefined) showToast(`Could not refresh: ${error.message}`)
    },
  }),
  mutationCache: new MutationCache({
    onError: (error) => showToast(`Could not save: ${error.message}`),
  }),
})

A query that fails on first load already shows its error in the page, so we only add a toast for failed background refreshes. Every failed mutation gets a toast from one place.

7. Mistakes to avoid ​

MistakeWhat goes wrongDo this
Forgetting to invalidate after a mutationThe page keeps showing old data until the next refetchonSuccess or onSettled invalidates the affected keys
Changing data from a query in placeYou change the cache's own object. Screens do not updateNever change it. Use setQueryData with a new value
Copying query data into useStateTwo copies, and the copy goes staleRead from useQuery directly
Creating new QueryClient() inside a componentEvery render makes a new empty cacheCreate it once, outside
Optimistic update with no cancelQueriesA slow in-flight refetch overwrites the optimistic valueawait cancelQueries first
Optimistic update with no rollbackA failed save leaves a lie on screenReturn { previous } and restore it in onError
Key missing a variable the function usesDifferent inputs share one cache entryPut it in the key

What the interviewer will push on ​

"How do you update data on the server with React Query?" useMutation with a mutationFn. Afterwards you invalidate the affected query keys so the cache refetches. Mention isPending for disabling the button.

"What does invalidateQueries do exactly?" Marks matching entries stale (prefix match on the key) and refetches the ones a component is currently using. The common slip is to say it deletes the data. It does not. The old data stays on screen until the new data arrives.

"Walk me through an optimistic update." onMutate: cancel in-flight queries, snapshot the old value, write the new value to the cache, return the snapshot. onError: restore the snapshot. onSettled: invalidate to sync with the server. A strong answer explains why each step is there, especially cancelQueries.

"When would you not use an optimistic update?" When the result depends on server logic you cannot predict (payments, inventory limits), or failure is likely or costly. Use a pending indicator instead.

"mutate vs mutateAsync?" mutate never throws; you handle results by callbacks and state. mutateAsync returns a promise you must catch.

"How do you combine React Router loaders with React Query?" The loader calls queryClient.ensureQueryData so the page has data on first draw, and the component uses useQuery with the same key to stay in sync afterwards.

One thing to volunteer: say that you choose between setQueryData (you know exactly what changed) and invalidateQueries (you do not), and that you design keys with a shared prefix so one invalidation can cover related lists and details.

Recall

  • Mutation = a write you trigger with mutate(variables). useMutation({ mutationFn, onSuccess, onError, onSettled }). States: isPending, isError, isSuccess, error, data, variables. Disable the button while isPending.
  • After a write the cache is out of date. queryClient.invalidateQueries({ queryKey }) marks everything starting with that key stale and refetches the ones on screen. Return its promise from onSuccess to keep isPending until the refetch ends.
  • setQueryData(key, newValue) writes into the cache when you already know the answer. Write when you know exactly what changed; invalidate when you do not.
  • mutate returns nothing. mutateAsync returns a promise: you must catch. Callbacks passed to mutate(vars, { onSuccess }) are for that call only.
  • Optimistic update: onMutate (cancel queries, snapshot with getQueryData, setQueryData the new value, return { previous }) → onError (restore) → onSettled (invalidate).
  • Simple optimistic UI for one place: draw mutation.variables while isPending. Nothing to roll back.
  • prefetchQuery on hover, and ensureQueryData in a router loader, put data into the cache before it is needed.
  • Global errors: QueryCache and MutationCache with onError.
  • Avoid: forgetting to invalidate, changing cached data in place, copying query data into state, creating the client inside a component.

Self-test: Why does invalidateQueries(['products']) also refresh a single product's detail? · Why do we cancelQueries before an optimistic update? · What does onError need from onMutate, and how does it get it? · When would you show variables instead of writing to the cache? · What does ensureQueryData do if the data is already cached?

Next: 6.4.12 teaches TanStack Router, the other popular router. It does the job of page 6.4.9 with one big difference: every route, parameter and search value is typed, so a broken link is a compile error, not a 404 in production.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Volume I — Technology
Part 0 — Retention & Notation
Part 1 — Foundations of Computation
Part 2 — Operating Systems
2.1 The Kernel
2.2 Processes
2.3 Threads & Scheduling
2.4 Concurrency Under the Hood
2.5 Memory Management
2.6 File Systems
2.7 Input/Output
2.8 Linux for Engineers
2.9 Windows & macOS in Practice
Part 3 — Languages, Compilers & Runtimes
3.6 JavaScript & V8
3.7 TypeScript
3.8 Node.js Internals
3.13 Python & CPython
3.14 FastAPI & Production Python
Part 4 — Data Structures & Algorithms
4.0 Classic Problems — Before NeetCode
4.4 Arrays & Hashing — Problems
4.5 Two Pointers
4.6 Sliding Window
4.8 Stack — Problems
4.9 Linked List — Problems
4.11 Binary Search — Problems
4.13 Trees
4.14 Tree — Problems
4.15 Trie — Problems
4.17 Heap — Problems
4.18 Backtracking — Problems
4.19 Graphs
4.20 Graph — Problems
4.21 Advanced Graph — Problems
4.23 1-D DP — Problems
4.24 2-D DP — Problems
4.26 Greedy — Problems
4.27 Interval — Problems
4.28 Math & Geometry — Problems
4.30 Bit Manipulation — Problems
Part 5 — Networking & the Web
5.3 IP
5.4 Transport
5.6 HTTP
Part 6 — Frontend Engineering
6.1 Browser Internals
6.2 HTML & CSS Mastery
6.3 JavaScript in the Browser
6.4 React, from First Component to Full Shop
6.5 Frameworks & Rendering
6.8 UI Engineering & Patterns
Part 7 — Databases & Storage
7.2 SQL Mastery
7.3 Storage Engine Internals
7.4 Transactions
7.5 NoSQL Taxonomy
7.8 Analytics & Big Data
Part 8 — Security, Identity & Cryptography
8.2 Cryptography
8.3 Protocols of Trust
8.4 Identity: AuthN & AuthZ
8.5 Application Security
8.6 Infrastructure Security
Part 9 — Software Design (LLD)
9.2 OOP Foundations
9.3 Design Principles
9.4 Design Patterns
9.5 Concurrency
9.6 API Design
9.7 LLD Interview Machines
9.9 Node/Express Production Playbook
Part 10 — Distributed Systems & HLD
10.7 Consistency & Consensus
10.8 Messaging & Microservices
10.14 Caching
Building blocks from the design seat
Part 11 — System Design Case Studies
Part 12 — AI & ML Engineering
12.1 What AI Engineering Is
12.2 The Math You Need
12.3 Classical Machine Learning
12.4 Data for ML
12.5 Deep Learning
12.6 Embeddings & Vector Search
12.7 Transformers & LLMs
12.8 Building with LLMs
12.9 Retrieval-Augmented Generation
12.10 Agents
12.11 Adapting Models
12.12 Production AI
12.13 Multimodal AI
12.14 AI Security & Governance
12.15 Case Studies & Capstone
Part 13 — Cloud, DevOps & Infrastructure
13.11 Git, from First Commit to Team Workflow
Part 14 — Containers: Docker & Kubernetes
14.1 Foundations
14.2 Docker
14.3 Kubernetes
14.4 Kubernetes on Azure
Part 15 — The Craft & Career
Nothing picked yet