Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

React
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
  • How a Web Page Works: HTML Tags, Elements and Attributes
  • Semantic HTML: header, nav, main, aside and footer as Page Landmarks
  • HTML Forms: Labels, Names, Input Types and Where the Data Goes (GET vs POST)
  • CSS Basics: Selectors, Which Rule Wins, and the Box Model
  • CSS Flexbox vs Grid: A Nav Bar, a Card Row and a Dashboard
  • Responsive CSS: Viewport, Mobile-First Media Queries, clamp() and Dark Mode with Tokens
  • JavaScript for People Who Already Code: Syntax, Modules and Five Surprises
  • JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries
  • Async JavaScript: Promises, async/await, fetch and Promise.all
  • JavaScript in the Page: the DOM, querySelector and Events
  • npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page
  • TypeScript Essentials: Types Checked, Then Erased (Interfaces, Unions, Generics)
  • Why React, JSX and Components: The Page as a Function of Data
  • React Props and Composition: Data Down, Calls Up, Children in the Slot
  • Routing With React Router: One Page, Many Addresses
  • React Component Tests With Vitest and Testing Library: Test What the User Sees
  • End-to-End Tests for a React App With Playwright: A Full Dress Rehearsal
  • Why AI-Built Websites All Look the Same, and Four Levels That Fix It
  • Visual Hierarchy, Spacing and the 8-Point Grid: Tell the Eye What to Read First
  • Colour, Contrast and Dark Palettes: 60-30-10, Semantic Tokens and Ratios You Can Compute
  • Typography That Sells: Type Scale, Line Length and Free Font Pairings
  • The UI Element Catalogue: Buttons to Toasts, Their Jobs, States and shadcn/ui Names
  • Design Tokens: Primitive and Semantic Tokens, from Figma to CSS to Tailwind
  • Tailwind CSS 4 in React: Utility Classes, Responsive Prefixes, Hover and Dark Mode
  • shadcn/ui in React: Components You Own, Edit and Commit
  • Design Tokens to a Tailwind Theme: Light and Dark Mode with @theme inline
  • Motion in React: Entrance, Hover, Exit and Layout Animations
  • A React Dashboard: Stat Cards, a Recharts Line Chart and a Sortable Table
  • Accessibility in Practice: Dialogs, Menus and the Keyboard in React
  • Reference-Driven Design: Extract a DESIGN.md From a Site You Admire and Build From It
  • Components, Variants and Variables: One Design System in Figma and in CSS
  • Figma MCP Server: Build a React Component From a Frame, Then Write It Back
  • Claude Design: From a Brief to a Clickable Prototype, Then Hand It Off to Claude Code
  • Critiquing AI-Generated UI: Six Checks for Every Screen
  • The AI Design Landscape: Prompt to UI, Prompt to App, and Design to Code
  • Your Brand Rules Folder: One Folder Every AI-Built Page Follows
  • The Best-Practice UI Prompt: Plain Sentences That Beat the Average AI Page
  • UI Ideas From Figma Make, Google Stitch and ChatGPT: One Prompt, Three Designs
  • Google Stitch From a Sketch or Screenshot: Show the Layout, Say What to Keep
  • Stitch to Figma to Code: Turn a Stitch Screen Into Code That Uses Your Tokens
  • Figma Make: Prompt to Prototype With a Four-Part Prompt
  • Upgrade a Dated UI From One Screenshot (or a Reference Image)
  • States and Feedback: Make Every Click Get an Answer
  • A Design-Loop Skill: Claude Screenshots, Scores and Fixes Its Own UI
  • Copy Without the AI Tells: A Copy Pass on a Landing Page
  • React State, Events, Lists and Conditional Rendering: Follow One Click
  • React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
  • Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
  • Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
  • React Context and Custom Hooks: Share One Value, Reuse the Logic
  • Server State With TanStack Query: One Key, One Request, One Cache
  • Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
  • Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
  • A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field
  • JWT Auth in a React Client With a FastAPI Backend: Log In, Carry the Token, Let the Server Decide
  1. Blog
  2. /
  3. React
  4. /
  5. Working with APIs

Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache

Add a book with useMutation and let invalidateQueries refetch the list, then make delete instant: snapshot, remove the row in 3 ms, roll back on a 404 and refetch the truth in onSettled.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Working with APIs

What you will learn

  • Send a POST with useMutation and refresh the list with invalidateQueries
  • Make a delete feel instant with onMutate and setQueryData
  • Roll back with a snapshot in onError and settle on the server's truth in onSettled
  • Explain why deleteBook must throw on a 404

Before you start

  • Server State With TanStack Query
  • React forms and event handlers

A query reads. It says "give me", and it can run again and again without changing anything. A mutation changes data on the server. It says "change this", and it runs once, only when the user asks.

The catch: right after a mutation, the list in your cache is out of date. The server now has 13 books and the cache still says 12, because nobody told it. This article adds a book, then makes a delete feel instant with a safe way back. It builds on the library app from Server State With TanStack Query, and every timing comes from a real Chrome run.

The server calls

// Hand-written server calls. Reading and changing
// both go through the same few lines.
export type Book = {
  id: number
  title: string
  author: string
  pages: number
}

export type NewBook = Omit<Book, 'id'>

export type BookPage = {
  content: Book[]
  page: { totalElements: number }
}

const json = { 'Content-Type': 'application/json' }

export async function getBooks(): Promise<BookPage> {
  const res = await fetch('/api/books?size=50')
  // fetch only throws on network errors, so we
  // turn a 4xx or 5xx answer into an error here
  if (!res.ok) throw new Error(`HTTP ${res.status}`)
  return res.json()
}

export async function addBook(book: NewBook) {
  const res = await fetch('/api/books', {
    method: 'POST',
    headers: json,
    body: JSON.stringify(book),
  })
  if (!res.ok) throw new Error(`HTTP ${res.status}`)
  return res.json() as Promise<Book>
}

export async function deleteBook(id: number) {
  const res = await fetch(`/api/books/${id}`, {
    method: 'DELETE',
  })
  // a 404 still resolves: throw, so onError runs
  if (!res.ok) throw new Error(`HTTP ${res.status}`)
}

addBook sends a POST with the book as JSON. JSON.stringify turns the object into text, because only text travels. deleteBook puts the id in the URL and sends no body. Both throw when res.ok is false. Keep that line in mind; the rollback later depends on it.

useMutation: a change, ready to send

import {
  useMutation,
  useQueryClient,
} from '@tanstack/react-query'
import { addBook } from './api'

export default function AddBook() {
  const qc = useQueryClient()
  const add = useMutation({
    mutationFn: addBook,
    // the list on screen is now out of date
    onSuccess: () =>
      qc.invalidateQueries({ queryKey: ['books'] }),
  })

  function submit(form: FormData) {
    add.mutate({
      title: String(form.get('title')),
      author: String(form.get('author')),
      pages: Number(form.get('pages')),
    })
  }

  return (
    <form action={submit}>
      <input name="title" placeholder="Title" />
      <input name="author" placeholder="Author" />
      <input name="pages" type="number"
        placeholder="Pages" />
      <button disabled={add.isPending}>
        {add.isPending ? 'Adding...' : 'Add book'}
      </button>
    </form>
  )
}
  1. Line 9 calls useMutation with mutationFn: addBook. Nothing is sent yet; the function is only kept. You get back add, with a mutate function and isPending set to false.
  2. The user types The Witches, Roald Dahl, 208 and clicks Add book. The form action hands submit the form data, and lines 17 to 21 build a plain object. Number turns the text "208" into the number 208.
  3. add.mutate(...) runs the mutation. isPending flips to true, so the button is disabled and says Adding... (no double clicks).

The POST goes out and the server answers 201 Created, with a Location header of /api/books/13 and the new book in the body. The id, 13, came from the server; we never sent one.

invalidateQueries: mark the list stale

Because the server said yes, onSuccess runs and calls invalidateQueries({ queryKey: ['books'] }). That does not fetch anything by itself. It stamps the ['books'] entry as stale. Three components read that entry and they are still on screen, so the cache fetches the list again right away:

after Add book: POST /api/books  ->  GET /api/books?size=50
count on screen: 13 books | list items: 13

The count goes from 12 to 13 and The Witches appears where the server's sort puts it. You did not patch the list by hand. And because onSuccess returns the refetch promise, the button keeps saying Adding... until the new list is in.

Waiting, or optimistic

Deleting a book can work two ways. The first waits for the server. With 300 ms of delay added to the network, the answer came at 330 ms, and all that time the row just sat there. The second is optimistic: change the screen first, check with the server in the background. With the same delay the row was gone at 2 ms, and the DELETE still finished at 330 ms in the background. With no added delay, on the local machine, the row was gone at 3 ms and the answer came at 39 ms.

Optimistic means you guess the server will say yes. So you also need a way back when it says no. Here is the whole hook:

import {
  useMutation,
  useQueryClient,
} from '@tanstack/react-query'
import { deleteBook, type BookPage } from './api'

const key = ['books']

type Cached = BookPage | undefined

// a NEW cached list, without one book
function without(old: Cached, id: number) {
  if (!old) return old
  const content = old.content.filter(
    (b) => b.id !== id,
  )
  const page = { totalElements: content.length }
  return { content, page }
}

// Optimistic: the row leaves the screen at once and
// a snapshot waits in case the server says no.
export function useDeleteBook() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: deleteBook,
    onMutate: async (id: number) => {
      await qc.cancelQueries({ queryKey: key })
      const previous = qc.getQueryData<BookPage>(key)
      qc.setQueryData(key, without(previous, id))
      return { previous }
    },
    // the server said no: put the snapshot back
    onError: (_err, _id, context) =>
      qc.setQueryData(key, context?.previous),
    // yes or no: refetch, so the screen ends on
    // what the server really has
    onSettled: () =>
      qc.invalidateQueries({ queryKey: key }),
  })
}

// BREAK IT: invalidate in onSuccess only, and after a
// failed delete the list is never fetched again
The optimistic delete lifecycle onMutate cancelQueries snapshot = previous setQueryData(without) DELETE /api/books/id 204: yes snapshot not needed 404: no, onError put snapshot back onSettled, yes or no: invalidateQueries GET the list again, the screen ends on the truth
Change the screen first, keep a snapshot, and always refetch at the end. The rollback undoes your guess; the refetch brings the truth.

Step 1: a snapshot first

Say we remove Mort, id 11. remove.mutate(11) runs onMutate before any request leaves. Line 28, cancelQueries, stops a refetch of ['books'] that might be on its way, because it could come back and undo our change. Line 29, getQueryData, reads the list as it is now and keeps it in previous. That is the snapshot, like saving a game before a hard level.

Step 2: the row leaves at once

without builds a new list where every book except id 11 is copied over, and works out the new total. previous is not touched, which is exactly why the snapshot works. Line 30, setQueryData, puts the new list in the cache, every reader re-renders, and Mort is gone from the page 3 ms after the click. Line 31 returns { previous }, and TanStack Query keeps it as this mutation's context.

Step 3: deleteBook must turn a 404 into an error

A DELETE for id 11 answers 204 No Content; res.ok is true and the promise resolves. A DELETE for a book that is already gone answers 404 with a small JSON body, and fetch still resolves, because a 404 is still an answer. Line 42 of api.ts throws when res.ok is false, and that throw is what makes the mutation fail and onError run. Without it, the rollback never happens.

Step 4: success or failure, then settle

On a 204 the snapshot is simply not needed. onSettled runs either way (settled means finished, with a yes or a no). It invalidates ['books'], a GET goes out, and the screen ends on what the server really has.

The failure case, for real

To make the server say no, another client deleted Persuasion (id 4) first and got a 204. Our page had loaded earlier, so Persuasion was still on our screen. Then we clicked Remove on it:

requests: DELETE /api/books/4  ->  GET /api/books?size=50
row events on screen: row gone at 3 ms -> row back at 26 ms -> row gone at 2564 ms
after the refetch: toast: "Could not delete" | row present: false | count: 10 books

The row left at once, the 404 came back, onError took previous from the context and put the snapshot back (the row returned at 26 ms). Then onSettled refetched, ten books came back without Persuasion, and the row left again with the message Could not delete. In this run the refetch was held for 2.5 seconds on purpose, so the in-between state could be captured.

The library page showing 11 books, with Persuasion by Jane Austen back in the list between Matilda and Pride and Prejudice, each row with a Remove button. No error message is shown yet.
After the 404, while the refetch is still on its way: the snapshot is back and Persuasion is in its place.
The library page showing 10 books and the red message Could not delete above the list. Persuasion is no longer in the list.
After the refetch: the server's list, 10 books, and the message Could not delete.

What the user clicks

  const remove = useDeleteBook()
  if (isPending) return <p>Loading books...</p>
  if (error) return <p>{error.message}</p>

  const books = data.content.filter(
    (b) => !author || b.author === author,
  )
  return (
    <>
      {remove.isError && (
        <p className="toast">Could not delete</p>
      )}
      <ul>
        {books.map((b) => (
          <li key={b.id}>
            <span>{b.title}</span>
            <small>{b.author}, {b.pages} pages</small>
            <button
              onClick={() => remove.mutate(b.id)}
            >
              Remove
            </button>
          </li>
        ))}
      </ul>
    </>
  )

(An excerpt of BookList.tsx.) Each row's Remove button calls remove.mutate(b.id) with that row's own id, and remove.isError shows the toast.

Common mistakes

  • Invalidating only in onSuccess. After a 404 nothing refetches, and the stale row stays on screen even though the server lost it long ago. Invalidate in onSettled.
  • Changing the cached list in place. If you mutate previous instead of building a new list, your snapshot changes too and there is nothing to roll back to.
  • Not throwing on a non-ok response. fetch resolves on a 404, so onError never runs.
  • Skipping cancelQueries. A refetch that was already in flight can land after your optimistic change and overwrite it.

Quick recap

StepCodeIn the run
Send a change onceuseMutation, mutatePOST answered 201, id 13
Refresh readersinvalidateQueries(['books'])12 books became 13
Change the screen firstonMutate + setQueryDatarow gone at 3 ms
Undo the guessonError puts previous backrow back at 26 ms
End on the truthonSettled invalidates10 books, Could not delete

Try it yourself

Move the invalidateQueries call from onSettled into an onSuccess, delete a book from a second tab, then click Remove on it in the first tab. Watch the stale row stay forever, then put onSettled back.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in React · 54 of 59

Previous
Server State With TanStack Query: One Key, One Request, One Cache
Next post
Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

Server State With TanStack Query: One Key, One Request, One Cache

Three components need the same list of books. Fetch it by hand and you get three requests; ask TanStack Query for one key and you get one. With real request counts, retries and a quiet refetch on tab focus.

Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval

Let the API's OpenAPI spec write your React client: Orval turns /v3/api-docs into TypeScript types, useGetBooks and a Zod schema, and a renamed field becomes error TS2339 at BookList.tsx line 26.

A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec

Build the React screen before the API exists: Orval writes MSW handlers and faker data from the spec, a service worker answers GET /api/books inside the browser, and npm run dev:real switches back to the real server.

A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy

Generate a React client from FastAPI's /openapi.json, then hit the CORS wall: the API answers 200 but the browser blocks it. Fix it with CORSMiddleware, or avoid it with the Vite proxy and one VITE_API_URL variable.

On this page

  • The server calls
  • useMutation: a change, ready to send
  • invalidateQueries: mark the list stale
  • Waiting, or optimistic
  • Step 1: a snapshot first
  • Step 2: the row leaves at once
  • Step 3: deleteBook must turn a 404 into an error
  • Step 4: success or failure, then settle
  • The failure case, for real
  • What the user clicks
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.