Vue Query 10 ⚡ Cache Invalidation & Direct Updates — Syncing UI after mutations with invalidateQueries, predicate filters, and setQueryData
The primary challenge of any caching system is keeping the client-side state synchronized with the server’s authoritative state. When a mutation occurs—like updating a profile, deleting a comment, or creating a new post—the cache becomes “stale.” If you leave the application as is, the user sees outdated data, which undermines the reliability of your interface. Vue Query addresses this with a dual-pronged strategy: Invalidation (asking the server for the latest data) and Direct Updates (manually patching the cache).
Invalidation is the most common and robust approach. By marking specific queries as stale, you instruct Vue Query to trigger a background refetch, ensuring the UI eventually reflects the server state. For scenarios where network overhead is a concern, or when the API response provides the exact new state of the object, Direct Updates allow you to modify the cache in-place without making a follow-up network request.
This chapter explores the sophisticated orchestration of cache management. We will delve into invalidateQueries for broad-stroke synchronization, the power of predicate filters for surgical cache manipulation, and the precision of setQueryData for instant UI updates. Mastering these tools transforms your data layer from a passive receiver of server responses into an active, synchronized engine of your application.
Key point: Use invalidateQueries to ensure eventual consistency by re-fetching data from the source of truth, and reserve setQueryData for high-performance scenarios where you have the new data available immediately and want to avoid unnecessary network latency.
Why exists
The Consistency Gap. Mutations operate independently of queries. When you send a POST request, the server updates its database, but the client’s cache remains unchanged. This “consistency gap” creates bugs where users see their old data despite a successful save. Invalidation closes this gap by synchronizing the two layers.
The Network Overhead Problem. Fetching all data from the server every time a tiny change occurs is expensive. In large lists, refetching 100 items just because 1 item was updated is wasteful. Direct Updates (setQueryData) exist to “patch” the cache locally, saving bandwidth and improving perceived performance.
The “Surgical Invalidation” Problem. Sometimes, you only want to invalidate queries that meet specific criteria—for example, invalidating all “Active” todos but leaving “Completed” ones cached. Standard invalidation would clear everything, causing unnecessary re-fetches. Predicate filters allow you to inspect the cache metadata or data structure before deciding to invalidate.
The Optimistic UI Requirement. To make an app feel “instant,” you must update the UI before the server has even finished processing the request. Direct updates enable this optimistic flow, allowing you to manipulate the cache structure programmatically to match the expected outcome of a mutation.
The Synchronization Complexity. In complex systems where multiple queries depend on the same underlying data, managing cache state becomes an orchestration challenge. These tools exist to provide a programmatic interface to manage the cache tree, preventing the “stale data” bugs that plague manual state management systems.
a. Invalidation Strategies (invalidateQueries)
The invalidateQueries method is the workhorse of the Vue Query ecosystem. When you invalidate a query, Vue Query performs two steps: it marks the query as “stale,” and if the query is currently being rendered (active), it automatically triggers a background refetch.
// Standard invalidation: marks all 'users' queries as stale
queryClient.invalidateQueries({ queryKey: ['users'] });
Invalidation works via prefix matching. If you invalidate ['users'], Vue Query will invalidate ['users', 'list'], ['users', 'detail', 1], and ['users', 'settings']. This is the power of the hierarchical key structure we established earlier. You can control this behavior using the exact option if you want to invalidate only that specific key.
// Only invalidate exactly ['users'], not the children
queryClient.invalidateQueries({ queryKey: ['users'], exact: true });
This is the safest way to ensure data integrity. While it does incur a network request, it guarantees that the client-side state is 100% aligned with the server. For the majority of applications, invalidateQueries is the correct default choice.
b. Predicate Filters (Surgical Targeting)
Sometimes, keys alone are not enough to identify the queries you need to invalidate. You might need to check the data already loaded in the cache. Predicate filters allow you to pass a function to invalidateQueries (or removeQueries, resetQueries) that receives the Query object, letting you inspect its internal state.
queryClient.invalidateQueries({
predicate: (query) => {
// Only invalidate queries related to 'todos'
// where the 'status' property in the query key is 'active'
return (
query.queryKey[0] === 'todos' &&
(query.queryKey[1] as any)?.status === 'active'
);
}
});
Predicates are exceptionally powerful for complex cache management. For example, if you have a massive paginated list and only want to invalidate pages where a specific “tenant_id” matches a filter, predicates are the only way to perform that check. They decouple your invalidation logic from strict key hierarchy, allowing you to react to the content of the cache rather than just its address.
c. Direct Cache Updates (setQueryData)
setQueryData is an imperative method that bypasses the network entirely. It allows you to manually inject data into the cache. This is typically used in the onSuccess or onMutate hooks of a mutation. When you have the updated object returned from your POST or PUT request, you can simply write it to the cache.
// Updating a single item in a list
queryClient.setQueryData(['todos', todoId], (oldData) => {
if (!oldData) return undefined;
return { ...oldData, title: 'Updated Title' };
});
This approach is extremely fast, but it places the burden of correctness on the developer. If you modify the cache incorrectly (e.g., changing the structure of an object in a way that breaks your UI components), you will introduce silent bugs.
The “functional update” pattern (passing a function to setQueryData instead of a static value) is highly recommended. It provides you with the oldData, allowing you to perform a partial update (a “patch”) on the existing object. This is significantly safer than overwriting the entire object, as it preserves any other properties that your components might be relying on.
Complete Example Session
// ============================================
// PART 1: BASIC INVALIDATION
// ============================================
const client = useQueryClient();
client.invalidateQueries({ queryKey: ['posts'] });
// ============================================
// PART 2: SURGICAL INVALIDATION (Exact)
// ============================================
client.invalidateQueries({ queryKey: ['posts', 1], exact: true });
// ============================================
// PART 3: PREDICATE FILTER
// ============================================
client.invalidateQueries({
predicate: (query) => query.queryKey[0] === 'posts' && query.state.data?.isPublished
});
// ============================================
// PART 4: DIRECT UPDATE (PATCH)
// ============================================
client.setQueryData(['posts', 1], (old: any) => ({
...old,
title: 'New Title'
}));
// ============================================
// PART 5: REMOVING QUERIES
// ============================================
// Completely delete from cache (avoids auto-refetch)
client.removeQueries({ queryKey: ['temp-data'] });
// ============================================
// PART 6: MUTATION INTEGRATION (onSuccess)
// ============================================
useMutation({
mutationFn: updatePost,
onSuccess: (data) => {
client.setQueryData(['posts', data.id], data); // Instant UI sync
client.invalidateQueries({ queryKey: ['posts'] }); // Background sync
}
});
// ============================================
// PART 7: RESETTING QUERIES
// ============================================
// Resets to initial state, ignoring current data
client.resetQueries({ queryKey: ['list'] });
// ============================================
// PART 8: MULTI-KEY INVALIDATION
// ============================================
client.invalidateQueries({ queryKey: ['users'] });
client.invalidateQueries({ queryKey: ['posts'] });
// ============================================
// PART 9: CONDITIONAL SETQUERYDATA
// ============================================
client.setQueryData(['list'], (old: any[]) =>
old?.filter(item => item.id !== deletedId)
);
// ============================================
// PART 10: CHECKING QUERY STATUS
// ============================================
const isCached = client.getQueryState(['posts', 1]);
if (isCached) console.log('Data exists:', isCached.data);
The example sequence above demonstrates the full spectrum of cache manipulation: basic invalidation, intelligent predicate filtering, and precise direct state patching.
Quick Reference
Invalidation Commands
| Command | Action |
|---|---|
invalidateQueries | Marks stale, triggers refetch (if active) |
refetchQueries | Force refetch immediately, regardless of stale state |
resetQueries | Sets query to initial state and refetches |
removeQueries | Deletes the query from cache entirely |
Predicate Logic
| Filter Type | Strategy | Use Case |
|---|---|---|
exact: true | Key Match | Specific query only |
predicate | Function | Check internal state, data content, or custom properties |
type | ‘active’ | ‘inactive’ | Only invalidate queries currently visible |
Direct Update Strategy
| Method | Approach | Best For |
|---|---|---|
setQueryData (Static) | Overwrite | Full replacements (e.g., list refresh) |
setQueryData (Func) | Patch | Partial updates (e.g., toggling one item) |
Best Practices
✅ Do This:
// Use functional updates to patch specific items
queryClient.setQueryData(['todos'], (old) => old.map(t => t.id === id ? newT : t)); // ✅
// Invalidate after mutations to ensure eventual consistency
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }); // ✅
// Use exact: true to avoid over-invalidating children
queryClient.invalidateQueries({ queryKey: ['todos'], exact: true }); // ✅
// Chain invalidation with direct updates for "Optimistic" results
queryClient.setQueryData(...); queryClient.invalidateQueries(...); // ✅
❌ Don’t Do This:
// Don't invalidate every single query in the app on every mutation
queryClient.invalidateQueries(); // (Performance killer!) // ❌
// Don't guess the cache structure in setQueryData
// (Always handle undefined/null cases) // ❌
// Don't mix up Invalidation (Refetch) and Direct Update (Cache Edit)
// (Invalidation is safer, Direct Update is faster) // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Invalidation Loop | Mutation triggers Invalidation -> Refetch -> Invalidation | Ensure invalidateQueries is in onSuccess, not in queryFn |
| UI Jitter | Updating cache with wrong shape | Match the exact data structure expected by components |
| Stale Data | Updating one key but not the dependent key | Invalidate the parent key to catch all children |
| Predicate Errors | Accessing data on a query that has no data | Always check query.state.data exists in predicate |
| Missing UI Update | Using setQueryData but not matching existing type | Ensure types are strictly maintained |
Real-World Examples
1. Simple Invalidation
queryClient.invalidateQueries({ queryKey: ['items'] })
2. Surgical Invalidation
queryClient.invalidateQueries({ queryKey: ['items', id], exact: true })
3. Optimistic “Like” Update
queryClient.setQueryData(['posts', id], (old) => ({ ...old, likes: old.likes + 1 }))
4. List Removal
queryClient.setQueryData(['items'], (old) => old.filter(i => i.id !== id))
5. Predicate Filter by Status
predicate: (q) => q.queryKey[0] === 'tasks' && q.state.data?.status === 'pending'
6. Refetching Active Queries Only
client.invalidateQueries({ queryKey: ['feed'], type: 'active' })
7. Direct Patch (Functional)
queryClient.setQueryData(['user'], (u) => ({ ...u, name: 'New Name' }))
8. Resetting Search Results
client.resetQueries({ queryKey: ['search'] })
9. Global Cache Clear
client.removeQueries()
10. Conditional Direct Update
if (client.getQueryData(['list'])) client.setQueryData(['list'], ...)
Visual
Invalidation vs. Direct Update
┌──────────────────────────────────────────────────────────┐
│ INVALIDATE (Eventual Consistency) │
│ Cache ──(stale)──► Network Request ──► Update Cache │
│ │
│ DIRECT UPDATE (Optimistic Consistency) │
│ Cache ──(overwrite)──────────────────► Update Cache │
└──────────────────────────────────────────────────────────┘
The Predicate Filter Logic
┌──────────────────────────────────────────────────────────┐
│ QUERY CACHE │
│ [Query A] ──┐ │
│ [Query B] ──┼──► PREDICATE FUNCTION │
│ [Query C] ──┘ if (query.data.active) ──► INVALIDATE! │
└──────────────────────────────────────────────────────────┘
Functional Update (The Patch Pattern)
┌──────────────────────────────────────────────────────────┐
│ setQueryData(['todo', 1], (old) => ...) │
│ │
│ [OLD DATA] ─────┐ │
│ │ │
│ PATCH ──► [NEW DATA] ──► CACHE UPDATE │
│ │ │
│ [LOGIC] ────────┘ │
└──────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Primary Invalidation | invalidateQueries |
| Precision Tool | predicate (filter function) |
| Speed Tool | setQueryData |
| Best Practice | Functional Updates (for patches) |
| Invalidation Strategy | Prefix-based matching |
| Safety | Always handle undefined in setQueryData |
Key takeaways:
- Prefer invalidation for correctness.
invalidateQueriesis the gold standard. It guarantees your UI matches the server, even if it introduces a small network round-trip . - Use
setQueryDatafor performance. If your API returns the updated entity (e.g., a PUT response), use that response to patch your cache immediately. It provides a lag-free UI experience . - Functional updates are safer. When using
setQueryData, always provide a function rather than a static value. This lets you “patch” your existing data rather than destroying it . - Master the predicate. When your key hierarchy isn’t enough, predicates allow you to inspect the cached data itself to decide what needs to be refreshed .
- Understand prefix matching. Invalidate parent keys to clean up child queries (e.g.,
['users']clears['users', 'list']), but useexact: truewhen you want to be surgical . - Always handle nulls. Since the cache might be empty or in the process of loading, always check for
oldDataexistence inside your functional updates to avoid runtime errors .
Remember: Cache management is the bridge between your server’s database and your user’s view. Master invalidation for safety and direct updates for speed, and your application will feel both perfectly synchronized and incredibly fast.
vue-query, cache-invalidation, setQueryData, predicate-filters
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!