| | |

Vue Query 11 ⚡ Optimistic Updates & Rollbacks — Updating the cache immediately via onMutate, cancelling in-flight queries, and rolling back on error

⏱️ Estimated read: 11 min | |

Optimistic updates are a high-level UI pattern where an application assumes a server request will succeed and updates the local state immediately before receiving a response. This technique eliminates the perceived latency of network requests, making the application feel instantaneous. In the context of Vue Query, this involves manually manipulating the query cache during the mutation lifecycle. While powerful, it introduces complexity, as the developer must handle scenarios where the server request fails, requiring a “rollback” to the previous known-good state to ensure data integrity.

The mechanism relies on the lifecycle hooks of the useMutation composable, specifically onMutate. When a mutation starts, onMutate is triggered, providing an opportunity to snapshot the current cache, cancel any outgoing queries that might interfere with the local state, and write the “optimistic” data into the cache. If the mutation fails, the onError hook uses the snapshot to restore the cache. Finally, onSettled ensures that the local state is eventually synchronized with the server by triggering a fresh refetch, regardless of whether the mutation succeeded or failed.

This chapter covers the implementation of optimistic updates using the TanStack Query library for Vue. We will explore the critical role of query cancellation in preventing race conditions, the structure of the mutation context used for rollbacks, and the proper sequencing of cache updates. By the end of this guide, you will be able to implement “snappy” interfaces that handle network errors gracefully without leaving the user in an inconsistent state.

Key point: Optimistic updates improve perceived performance by updating the local cache immediately using onMutate, but require manual query cancellation to prevent overwrites and a rollback mechanism in onError to restore the previous state if the server request fails.


Why exists

The latency perception problem. Even with fast networks, there is a delay between a user clicking a button and a server confirming a data change. This “micro-lag” can make an app feel sluggish. Optimistic updates remove this gap by providing immediate visual feedback, tricking the human brain into perceiving zero latency.

The loading spinner fatigue. Modern users are increasingly impatient with global loading spinners or “blocked” UIs. By updating the data optimistically, you keep the user in the “flow” of the application, allowing them to continue interacting with the interface while the background network requests catch up.

The race condition problem. When updating data optimistically, a background refetch could start and overwrite your “fake” optimistic data with “old” server data before the mutation finishes. Vue Query provides query cancellation tools to ensure that optimistic state is preserved until the server confirms the truth.

The synchronization conflict. If a mutation fails but the UI has already “succeeded,” the application is lying to the user. Rollbacks exist to resolve this conflict. They provide a standardized way to undo the local “lie” and return the UI to reality as soon as the failure is detected.

The batching and sequencing trade-off. Optimistic updates are difficult to manage manually with traditional state management. Vue Query encapsulates the logic into the mutation lifecycle, making it easier to manage the “Snapshot -> Update -> (Success/Fail) -> Refetch” sequence without polluting global stores with temporary “fake” data.


a. The onMutate Lifecycle and Cache Snapshotting

The onMutate hook is the entry point for optimistic updates. It runs before the actual mutation function (the API call) is executed. Its primary responsibility is to “snapshot” the current state of the cache so that it can be restored if things go wrong. In Vue Query, you return this snapshot from onMutate, and it becomes available as the “context” in subsequent hooks like onError and onSettled.

To implement this, you first need to stop any active queries for the specific data you are about to change. If you don’t cancel them, an in-flight fetch might return and overwrite your optimistic update with the old server state. After cancellation, you use queryClient.setQueryData to manually push the new, “optimistic” value into the cache.

const { mutate } = useMutation({
  mutationFn: updateTodo,
  onMutate: async (newTodo) => {
    // 1. Cancel any outgoing refetches (so they don't overwrite our optimistic update)
    await queryClient.cancelQueries({ queryKey: ['todos'] })

    // 2. Snapshot the previous value
    const previousTodos = queryClient.getQueryData(['todos'])

    // 3. Optimistically update to the new value
    queryClient.setQueryData(['todos'], (old) => {
      return old.map(t => t.id === newTodo.id ? { ...t, ...newTodo } : t)
    })

    // 4. Return the context object with the snapshot
    return { previousTodos }
  },
})

The logic here is purely local. We are manipulating the JavaScript object held in the memory cache of the queryClient. The previousTodos object is passed along the “context pipe” to the other lifecycle hooks.


b. Handling Failures with onError Rollbacks

If the mutationFn throws an error (e.g., a 500 server error or a timeout), the onError hook is called. This hook receives the error, the variables passed to the mutation, and—most importantly—the context object returned by onMutate. To perform a rollback, you simply use setQueryData again, but this time you set the cache back to the previousTodos snapshot stored in the context.

onError: (err, newTodo, context) => {
  // Restore the cache to the state it was in before onMutate ran
  if (context?.previousTodos) {
    queryClient.setQueryData(['todos'], context.previousTodos)
  }
  // Optionally: Show a toast or notification to the user
  console.error("Mutation failed, rolling back!", err)
},

Without this step, the UI would remain in the “fake” successful state while the server remained in the “old” state. This creates a dangerous “state drift” where the user believes they have saved their work when they haven’t. The rollback ensures that the UI eventually aligns with the truth of the server, even if that truth is a failure.

It is common practice to trigger a notification here. Since the UI will suddenly “jump” back to the previous state, the user needs to know why. A toast message saying “Failed to update, please try again” explains the visual jump.


c. Finalizing with onSettled and Query Cancellation

The onSettled hook runs regardless of success or failure. It is the “cleanup” phase of the mutation. Its primary job in an optimistic update pattern is to invalidate the query. Invalidating ensures that, even if our rollback or our optimistic update was slightly off, the application fetches the absolute “source of truth” from the server one last time.

Query cancellation is the often-overlooked hero of this process. If the user clicks “Save” and then immediately navigates or triggers another fetch, multiple network requests might be competing. By calling queryClient.cancelQueries(['todos']), we tell Vue Query to ignore the results of any currently active fetches for that key, ensuring our manual cache manipulation is the only thing the UI sees during the transition.

onSettled: () => {
  // Always refetch after error or success to sync local cache with server
  queryClient.invalidateQueries({ queryKey: ['todos'] })
},

Combining these three hooks creates a resilient loop:

  1. onMutate: Stop the world, take a picture, and apply the “fake” change.
  2. onError: If the “fake” change failed on the server, use the picture to put things back.
  3. onSettled: Regardless of the outcome, ask the server for the latest data just to be 100% sure.

Complete Example Session

// ============================================
// PART 1: THE DATA TYPE
// ============================================
interface Task { id: number; text: string; done: boolean }

// ============================================
// PART 2: THE API CALL
// ============================================
const updateTaskApi = async (task: Task) => {
  const response = await fetch(`/api/tasks/${task.id}`, {
    method: 'PATCH',
    body: JSON.stringify(task)
  });
  if (!response.ok) throw new Error('Server crash');
  return response.json();
}

// ============================================
// PART 3: THE MUTATION SETUP
// ============================================
const queryClient = useQueryClient();

const { mutate } = useMutation({
  mutationFn: updateTaskApi,

  // ============================================
  // PART 4: START OPTIMISTIC (onMutate)
  // ============================================
  onMutate: async (updatedTask: Task) => {
    // 5. PREVENT RACE CONDITIONS
    await queryClient.cancelQueries({ queryKey: ['tasks'] });

    // 6. CAPTURE THE PAST
    const previousTasks = queryClient.getQueryData<Task[]>(['tasks']);

    // 7. FAKE THE FUTURE
    queryClient.setQueryData(['tasks'], (old: Task[] | undefined) => {
      return old?.map(t => t.id === updatedTask.id ? { ...t, ...updatedTask } : t);
    });

    // 8. PASS CONTEXT
    return { previousTasks };
  },

  // ============================================
  // PART 9: THE ROLLBACK (onError)
  // ============================================
  onError: (err, updatedTask, context) => {
    if (context?.previousTasks) {
      queryClient.setQueryData(['tasks'], context.previousTasks);
    }
  },

  // ============================================
  // PART 10: THE SYNC (onSettled)
  // ============================================
  onSettled: () => {
    queryClient.invalidateQueries({ queryKey: ['tasks'] });
  }
});

This sequence covers the snapshot, the update, the cancellation, the context passing, the rollback, and the final synchronization.


Quick Reference

The Mutation Context Pipe

HookReceivesReturnsPurpose
onMutateMutation variablesContext objectSnapshot and fake update
onSuccessResult, Variables, ContextNothingSide effects on success
onErrorError, Variables, ContextNothingRollback using context
onSettledResult/Error, Variables, ContextNothingFinal cache invalidation

Vital Functions

FunctionUsageWhy?
cancelQueriesawait q.cancelQueries({key})Prevent overwriting fake data with old server data
getQueryDataq.getQueryData(key)Capture the snapshot for the rollback
setQueryDataq.setQueryData(key, updater)Perform the “fake” optimistic update
invalidateQueriesq.invalidateQueries({key})Force a sync with server at the end

Best Practices

✅ Do This:

// Await query cancellation before setting data
await queryClient.cancelQueries({ queryKey: ['data'] });       // ✅

// Return the snapshot object from onMutate
return { previousData };                                       // ✅

// Check if context exists before rolling back
if (context?.previousData) { ... }                             // ✅

// Always invalidate in onSettled to ensure consistency
onSettled: () => queryClient.invalidateQueries(...)            // ✅

❌ Don’t Do This:

// Don't skip cancellation; it leads to flickering
queryClient.setQueryData(...); // skipping cancelQueries       // ❌

// Don't perform side effects (toasts) in onMutate
onMutate: () => { alert('Saved!'); } // Too early!             // ❌

// Don't forget to return the snapshot
onMutate: () => { queryClient.setQueryData(...) } // return?   // ❌

// Don't use optimistic updates for critical financial actions
// (Only for UI "snappiness" in low-risk views)                // ❌

Common Pitfalls

PitfallWhy It HappensFix
UI “Flickers” back to old datacancelQueries was not awaitedUse await queryClient.cancelQueries
Rollback failsSnapshot wasn’t returned from onMutateEnsure onMutate returns the data object
Data stays “fake” foreverMissing invalidateQueries in onSettledAlways invalidate at the end of the lifecycle
Duplicate items appearsetQueryData logic appends instead of updatesCheck ID equality in the mapping function
Slow rollbackComplex cache structuresKeep snapshots as simple as possible

Real-World Examples

1. Toggle Switch (Boolean)

Optimistically flipping a “Published” status toggle.

2. Likes / Heart Button

Incrementing a like count locally while the server processes the interaction.

3. Task Completion

Moving a task from “Active” to “Done” in a list instantly.

4. Inline Name Editing

Updating a user’s name in a profile header as they type or on “Blur”.

5. Drag and Drop

Moving an item between columns in a Kanban board before the API confirms.

6. Deleting an Item

Removing a row from a table immediately and restoring it if the delete fails.

7. Comment Posting

Appending a new comment to a list with a “Sending…” status visually.

8. Star Rating

Updating the filled stars in a review component immediately.

9. Shopping Cart Quantity

Increasing the count of an item in the cart summary instantly.

10. Folder Renaming

Changing a folder name in a sidebar tree structure for zero-latency feel.


Visual

The Optimistic Update Timeline

USER CLICKS [SAVE]
      │
      ▼
┌──────────────────────────────────────────────┐
│  onMutate (Phase 1)                          │
│  1. await cancelQueries(['items'])           │
│  2. const snapshot = getQueryData(['items']) │
│  3. setQueryData(['items'], fakeData)        │
│  4. return { snapshot }                      │
└──────────────────────────────────────────────┘
      │
      ├───────────────────────┐
      ▼                       ▼
[ API SUCCESS ]        [ API FAILURE ]
      │                       │
      │                ┌───────────────────────┐
      │                │  onError (Phase 2)    │
      │                │  setQueryData(        │
      │                │    ['items'],         │
      │                │    context.snapshot   │
      │                │  )                    │
      │                └───────────────────────┘
      │                       │
      └──────────┬────────────┘
                 ▼
┌──────────────────────────────────────────────┐
│  onSettled (Phase 3)                         │
│  invalidateQueries(['items'])                │
│  (UI syncs with absolute server truth)       │
└──────────────────────────────────────────────┘

Race Condition Prevention (The Overwrite)

WRONG (No Cancellation):
Refetch Start ───► [WAITING] ────────────────────► [OLD DATA ARRIVES]
User Action   ───────────► [OPTIMISTIC DATA] ────────┘ (Overwritten!)

RIGHT (With Cancellation):
Refetch Start ───► [WAITING] ───┐ (CANCELLED!)
User Action   ───────────► [OPTIMISTIC DATA] ───► [SYNC FROM SERVER]

Summary

ItemValue
HookuseMutation
Key LifecycleonMutate
MechanismCache manipulation
FallbackRollback via context
Final ActionInvalidation
Pre-requisiteQuery Cancellation

Key takeaways:

  • Speed is a perception. Optimistic updates use onMutate to eliminate perceived network latency, making the UI feel native and “snappy.”
  • Cancellation is non-negotiable. You must await cancelQueries to prevent background fetches from clobbering your optimistic data with stale server info .
  • The Context Pipe is the safety net. Returning a snapshot from onMutate allows onError to restore the previous state perfectly if the mutation fails .
  • onSettled ensures truth. Always trigger a refetch at the end of the mutation lifecycle to fix any minor discrepancies between your optimistic “guess” and the server’s reality .
  • User feedback is still required. If an optimistic update rolls back, the user should be notified via a toast or alert to explain the sudden change in data .
  • Manual cache control is powerful. Vue Query gives you direct access to the queryClient, making it possible to manipulate any part of your application’s state during a mutation .

Remember: Optimistic updates are a promise to the user that “I will save this.” Rollbacks are the way you keep that promise honest if the network fails. Use them together to create high-performance, resilient Vue applications.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!