Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 38 ยท Optimistic Updates

Optimistic UI with Variables

The simplest optimistic update in TanStack Query v5: render the pending mutation's variables in the UI while the request runs, with no cache writes or rollback code.

Waiting for a server before the screen changes makes an app feel slow, even when the network is fine. An optimistic update assumes the request will succeed and shows the result immediately. If the request fails, the UI goes back to the truth.

TanStack Query v5 offers two ways to do this. The more powerful one edits the cache (next lesson). The simpler one uses only the mutation's own state: while the mutation is pending, variables holds what you are sending, so you can render it right away next to the real data. There is nothing to roll back, because the optimistic item never entered the cache. This lesson covers that approach.

How it works

useMutation returns isPending, variables, isError and reset along with mutate. When you call mutate({ text: "Buy milk" }):

  1. isPending becomes true and variables is { text: "Buy milk" }.
  2. You render a temporary row from variables.
  3. On success you invalidate the list query. When the fresh list arrives, the temporary row disappears and the real row replaces it.
  4. On error, isError is true, variables still holds the failed input, and you can show the row in red with a Retry button.
sequenceDiagram
  participant U as User
  participant UI as Component
  participant M as useMutation
  participant S as Server
  U->>UI: click Add
  UI->>M: mutate(variables)
  M-->>UI: isPending = true
  UI-->>U: pending row (from variables)
  M->>S: POST
  S-->>M: 200 OK
  M->>UI: invalidate list, refetch
  UI-->>U: real row replaces pending row

The pending row is rendered from mutation state alone; the cache changes only when the server confirms.

A todo list with a pending row

The fake server below keeps the todos in memory. The "Fail the next request" checkbox makes the next save throw, so you can see the error state.

Pending row from variables

Add a todo: the grey row shows at once, and one second later the list refetches and the row becomes a normal item. Tick the checkbox first and the row turns red with a Retry button. The rollback is automatic, because the list in the cache never contained the failed item.

Where variables is available

  • On the useMutation result: add.variables, add.isPending, add.isError.
  • In onSuccess(data, variables), onError(error, variables) and onSettled(data, error, variables).
  • For lists of mutations anywhere in the app: useMutationState (next section).

After a mutation settles successfully, variables still has the last input until you call reset() or mutate again. That is why the pending row above checks isPending, not just variables.

Showing pending items elsewhere with useMutationState

If the list and the form are in different components, the form's useMutation result is not reachable from the list. Give the mutation a mutationKey and read all matching mutations with useMutationState:

JSX
const pending = useMutationState({
  filters: { mutationKey: ["addTodo"], status: "pending" },
  select: (mutation) => mutation.state.variables,
});
// pending is an array of variables, one per in-flight mutation
JSX
useMutation({ mutationKey: ["addTodo"], mutationFn: addTodo })

This also handles several in-flight mutations at once: pending.map(...) renders one temporary row per click.

Several pending rows with useMutationState

Click the button three times fast: three grey rows appear and turn into real rows as the server responds. The list component never received the form's mutation object.

Limits of the variables approach

It is deliberately simple, and that shows in a few situations:

  • Ordering and editing. A pending row is added to the end. If the real result should sit in the middle of a sorted list, or the update changes an existing row, you need cache edits instead (next lesson).
  • Several places show the same data. A count in the header, a detail page and the list must all update, but only the list renders pending rows. Cache edits update every observer of the key at once.
  • Brief flicker. Between the mutation finishing and the refetch arriving, the pending row is gone but the real row is not there yet. Await the invalidation to avoid it: onSettled: () => queryClient.invalidateQueries(...) returns a promise, and a mutation callback that returns a promise keeps the mutation in pending until it resolves.

That last tip is the key one. Return the promise (no braces, or an explicit return) and the pending row stays until the refreshed list is in place.

When to choose this approach

Choose variables when the optimistic change touches one place and you just want to add something. Choose cache updates when the change touches existing items, several components or sorted data. Many apps use both: variables for "create", cache updates for "toggle" and "delete".

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main advantage of the variables approach to optimistic UI?

    The pending row is drawn from mutation state; the cache stays correct. On failure you simply stop drawing it.
  2. 2. How do you render a pending item from a different component than the one that called useMutation?

    useMutationState reads mutations across the whole QueryClient, filtered by mutationKey and status.
  3. 3. How do you avoid a flicker between the pending row disappearing and the refetched list arriving?

    A mutation callback that returns a promise is awaited, so isPending stays true until the list is fresh.
  4. 4. Which case is a poor fit for the variables approach?

    Changing an existing item shown in several places is best done with a cache update so all observers change together.

Summary

  • While a mutation is pending, variables holds the input; render it as a temporary row.
  • On error, show the same input with a Retry button; nothing needs rolling back.
  • mutationKey plus useMutationState shows pending items from other components and handles several in-flight mutations.
  • Return the invalidation promise from onSettled to avoid a flicker.
  • Use cache updates when the change is to existing items or appears in several places.

Next: Optimistic Updates in the Cache