| | |

Vue Query 02 ⚡ Setup & VueQueryPlugin — Configuring QueryClient, global defaultOptions, and inspecting cache states with Vue Query Devtools

⏱️ Estimated read: 13 min | |

Setting up Vue Query is the foundational step in moving from imperative data fetching to declarative server state management. While the library can be used with zero configuration, its true power is unlocked when you tailor the QueryClient to the specific needs of your application. The QueryClient acts as the central brain and storage container for all cached data, managing the lifecycle of every request, from the initial trigger to final garbage collection. By configuring this client globally through the VueQueryPlugin, you establish a consistent set of rules that govern how data is treated across your entire component tree.

Configuring global default options is a strategic decision that prevents the need for repetitive, boilerplate settings in every useQuery call. Most production applications do not want the default behavior of “immediate staleness” (where data is considered old the second it is fetched). Instead, developers use the global configuration to set sensible defaults for stale times, garbage collection intervals, and retry logic. This centralization ensures that your application behaves predictably, reducing “network chatter” and providing a smoother experience for the user by reusing cached data more aggressively.

Visualizing the state of your cache is equally important during development. Server state is often invisible, making it difficult to debug why a refetch happened or why a specific piece of data is still in memory. The Vue Query Devtools provide a powerful graphical interface to inspect the internal workings of the QueryClient. This tool allows you to see every query key, track its status (fresh, stale, fetching, or inactive), and even manually trigger refetches or cache invalidations. It is an indispensable part of the setup process that provides transparency to the otherwise opaque world of asynchronous state.

This chapter walks through the complete installation and configuration process for Vue Query. We will examine the structure of the QueryClient, the various global options available for tuning performance, and the integration of the official Devtools. By the end of this guide, you will have a robust, production-ready setup that provides a clean architectural foundation for all future server-side interactions.

Key point: The QueryClient is the single source of truth for the cache; configuring it via defaultOptions in the VueQueryPlugin allows you to define global behaviors for data freshness and retry logic that apply to every query in your application.


Why exists

The Centralized Governance problem.
Without a central client, every component would have its own isolated cache. This would lead to redundant requests and inconsistent data. The QueryClient exists to provide a global registry where all components can share the same data. By using the VueQueryPlugin, you ensure that this registry is available to every Vue component through the injection system, maintaining a single, unified view of the server state.

The Configuration Fatigue problem.
In a large app, you might have hundreds of queries. Setting staleTime: 10000 on every single one of them is tedious and prone to error. Global defaultOptions exist to solve this. They allow you to define a baseline behavior—such as “consider all data fresh for 30 seconds”—at the root level. This keeps your individual useQuery calls clean and focused strictly on the data they need, while the infrastructure handles the timing.

The Hidden Cache problem.
Asynchronous state is notoriously difficult to debug because it lives in memory, not in the DOM. You cannot “see” the cache by looking at the page. The Vue Query Devtools exist to solve the observability problem. They provide a real-time dashboard where you can inspect every query’s data, its current state, and its history, making it easy to identify performance bottlenecks or stale data issues.

The Resilience problem.
Network requests fail for many reasons—temporary blips, server timeouts, or spotty mobile connections. Implementing custom retry logic for every fetch is complex. Vue Query’s setup includes a global retry configuration that automatically handles re-attempts with exponential backoff. This exists to make your application resilient by default, ensuring that a single dropped packet doesn’t result in a broken UI for the user.

The Garbage Collection problem.
Caches can grow indefinitely if not managed, leading to memory leaks and browser slowdowns. The gcTime (Garbage Collection Time) setting in the client exists to automate memory management. It ensures that data that is no longer being used by any active component is eventually purged from memory, keeping the application’s footprint small and efficient over long user sessions.

The Interaction Consistency problem.
Should the app refetch when the user refocuses the window? Should it refetch when the network reconnects? These are high-level UX decisions that should be consistent across the whole app. The setup process allows you to define these “revalidation triggers” globally, ensuring that the entire application reacts to environment changes in the same way, providing a predictable and professional user experience.


a. Initializing the QueryClient and VueQueryPlugin

The setup begins in your application’s entry file (usually main.ts). You must create an instance of the QueryClient and then register the VueQueryPlugin. This plugin uses Vue’s provide/inject mechanism to make the client available to all components.

import { createApp } from 'vue'
import { QueryClient, VueQueryPlugin } from '@tanstack/vue-query'
import App from './App.vue'

// 1. Create the client instance
const queryClient = new QueryClient()

const app = createApp(App)

// 2. Install the plugin and provide the client
app.use(VueQueryPlugin, {
  queryClient,
})

app.mount('#app')

The QueryClient is the engine that holds the cache. When you call useQuery in a component, the library looks for this provided client to store or retrieve data. If you don’t provide a queryClient to the plugin, it will create one for you with default settings, but creating your own instance is the standard practice as it allows for customization and easier testing.

In a modern Vue 3 application, the plugin also handles some internal cleanup and ensures that the cache is properly disposed of when the application is unmounted. This is particularly important for testing or multi-app setups where memory isolation is critical.


b. Global Configuration with defaultOptions

The most important part of the setup is the defaultOptions object. This allows you to override the library’s defaults for every query in your application. The options are divided into queries (for fetching) and mutations (for updating).

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      // Data is considered fresh for 1 minute
      staleTime: 1000 * 60,
      // Unused data is kept in memory for 5 minutes
      gcTime: 1000 * 60 * 5,
      // Retry failed requests 3 times before showing error
      retry: 3,
      // Refetch when the user refocuses the window (tab)
      refetchOnWindowFocus: true,
      // Refetch if the network goes down and comes back up
      refetchOnReconnect: true,
    },
    mutations: {
      // Mutations usually shouldn't retry automatically
      retry: false,
    },
  },
})

The difference between staleTime and gcTime is a common point of confusion. staleTime is about freshness: it defines how long the data remains valid before a background refetch is needed. gcTime is about existence: it defines how long the data stays in the cache after all components using that query have unmounted.

By setting a global staleTime, you effectively turn off the “aggressive refetching” default. If staleTime is 60,000ms, and a user navigates between two pages using the same data within that minute, Vue Query will serve the cached data instantly without even attempting a network call.


c. Integrating Vue Query Devtools

The Vue Query Devtools are a separate package that provides a visual interface for inspecting the cache. They are only included in development builds and are automatically excluded from production bundles, so you don’t need to worry about extra weight in your final app.

npm install @tanstack/vue-query-devtools

To use them, you simply import the VueQueryDevtools component and place it in your App.vue. It is usually placed at the very bottom of the template.

<script setup>
import { VueQueryDevtools } from '@tanstack/vue-query-devtools'
</script>

<template>
  <nav>...</nav>
  <RouterView />

  <!-- This renders a small toggle button in the bottom corner -->
  <VueQueryDevtools />
</template>

When you open the Devtools in your browser, you will see a list of all active and inactive queries. Each entry shows its Query Key, the actual Data stored, and its current Status.

  • Fresh: Data is within the staleTime. No refetch will happen.
  • Stale: Data is outside the staleTime. A refetch will trigger next time the query is used.
  • Fetching: A network request is currently in progress.
  • Inactive: No components are currently using this data, but it is still in the cache (until gcTime expires).

The Devtools allow you to “Force Refetch” any query, which is incredibly useful for testing how your UI reacts to data updates. You can also “Invalidate” a query to see it transition from fresh to stale.


Complete Example Session

// ============================================
// PART 1: INSTALLATION (Terminal)
// ============================================
// npm install @tanstack/vue-query @tanstack/vue-query-devtools

// ============================================
// PART 2: CLIENT CREATION (src/queryClient.ts)
// ============================================
import { QueryClient } from '@tanstack/vue-query'

export const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5 * 60 * 1000, // 5 minutes
      gcTime: 10 * 60 * 1000,    // 10 minutes
      retry: (failureCount, error: any) => {
        // Only retry if it's not a 404
        return error.response?.status !== 404 && failureCount < 3
      },
    },
  },
})

// ============================================
// PART 3: PLUGIN REGISTRATION (main.ts)
// ============================================
import { createApp } from 'vue'
import { VueQueryPlugin } from '@tanstack/vue-query'
import { queryClient } from './queryClient'
import App from './App.vue'

const app = createApp(App)
app.use(VueQueryPlugin, { queryClient })
app.mount('#app')

// ============================================
// PART 4: APP-LEVEL DEVTOOLS (App.vue)
// ============================================
/*
<template>
  <main><RouterView /></main>
  <VueQueryDevtools :initial-is-open="false" />
</template>
<script setup>
import { VueQueryDevtools } from '@tanstack/vue-query-devtools'
</script>
*/

// ============================================
// PART 5: CONFIGURING CACHE PERSISTENCE (Advanced)
// ============================================
// This allows cache to survive page refreshes via LocalStorage
/*
import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'
import { persistQueryClient } from '@tanstack/query-persist-client-core'

const persister = createSyncStoragePersister({ storage: window.localStorage })
persistQueryClient({ queryClient, persister })
*/

// ============================================
// PART 6: OVERRIDING GLOBALS LOCALLY
// ============================================
// Even with globals, you can be specific in a component
/*
const { data } = useQuery({
  queryKey: ['critical-data'],
  queryFn: fetcher,
  staleTime: 0, // Always refetch this specific one
})
*/

// ============================================
// PART 7: LOGGING GLOBAL ERRORS
// ============================================
/*
const queryClient = new QueryClient({
  queryCache: new QueryCache({
    onError: (error) => console.error(`Global Query Error: ${error.message}`),
  }),
})
*/

// ============================================
// PART 8: GLOBAL REFETCH ON FOCUS TOGGLE
// ============================================
/*
queries: {
  refetchOnWindowFocus: process.env.NODE_ENV === 'production',
}
*/

// ============================================
// PART 9: THE QUERY STATUS COLOR CODES
// ============================================
// Fresh = Green
// Stale = Yellow
// Fetching = Blue
// Inactive = Gray

// ============================================
// PART 10: SUMMARY OF SETUP
// ============================================
// 1. Client instance with defaultOptions created.
// 2. VueQueryPlugin provided to the app.
// 3. Devtools component mounted at root.
// 4. Global behaviors defined for freshness and retries.

The parts above cover the transition from simple plugin installation to complex global configurations, including retry logic, global error handling, and visual debugging with devtools.


Quick Reference

defaultOptions Properties

OptionTypeDefaultDescription
staleTimenumber0Time until data is “old”
gcTimenumber5 minTime until unused data is deleted
retryboolean|number|fn3Retry logic for failed requests
refetchOnWindowFocusbooleantrueUpdate when user returns to tab
refetchOnReconnectbooleantrueUpdate when network recovers

VueQueryPlugin Options

OptionTypeDescription
queryClientQueryClientThe client instance to use
queryClientConfigObjectConfig if creating client inline

Devtools Configuration

PropTypeDefaultDescription
initial-is-openbooleanfalseWhether to start expanded
button-positionstringbottom-rightToggle button placement
positionstringbottomPanel placement

Best Practices

✅ Do This:

// Set a global staleTime > 0 to avoid constant refetching
queries: { staleTime: 30000 }                                  // ✅

// Define your QueryClient in a separate file for testability
export const queryClient = new QueryClient({ ... });           // ✅

// Use the Devtools in every development project
<VueQueryDevtools />                                           // ✅

// Disable retries for mutations to prevent unintended duplicate writes
mutations: { retry: false }                                    // ✅

❌ Don’t Do This:

// Don't leave staleTime at 0 for data that rarely changes
// (This hammers your API unnecessarily)                       // ❌

// Don't define the QueryClient inside the main.ts file directly
// (Makes it hard to import in other files like tests)         // ❌

// Don't use window-focus refetching for very expensive APIs
refetchOnWindowFocus: false                                    // ❌

// Don't forget to install the Devtools package
// (It is not included in the core library)                   // ❌

Common Pitfalls

PitfallWhy It HappensFix
Data always “Stale”Default staleTime is 0Set a global staleTime (e.g., 5 min)
Devtools missingPackage not installed or component not in App.vuenpm install @tanstack/vue-query-devtools
Infinite RetriesWrong retry configurationSet retry: 3 or use a function to filter errors
Memory BloatgcTime set too highKeep gcTime at the default (5 min) or lower
Plugin erroruseQuery called before plugin installEnsure app.use(VueQueryPlugin) is in main.ts
Unexpected RefetchrefetchOnWindowFocus is activeSet to false in defaultOptions if not wanted

Real-World Examples

1. Standard Production Setup

const queryClient = new QueryClient({
  defaultOptions: { queries: { staleTime: 1000 * 60 * 5 } }
});

2. Mobile-Friendly Setup (Lower cache time)

queries: { gcTime: 1000 * 60 * 2 } // Keep cache small

3. High-Security App (No refocus refetch)

queries: { refetchOnWindowFocus: false }

4. Retry only on Network Errors

retry: (count, err) => err.message === 'Network Error' && count < 3

5. Mutation Global Config

mutations: { onError: (e) => notify(e.message) }

6. Devtools Bottom-Left Placement

<VueQueryDevtools position="bottom-left" />

7. Global Query Cache Logging

new QueryCache({ onSuccess: (data) => log(data) })

8. Conditional Stale Time (Dynamic)

staleTime: isVipUser ? 60000 : 0

9. Persisted Cache Setup

const client = new QueryClient(); persistQueryClient({ client, ... });

10. Manual Client Provision (Plugin)

app.use(VueQueryPlugin, { queryClient: myCustomClient });

Visual

The QueryClient Hierarchy

┌──────────────────────────────────────────────────────────┐
│  QUERY CLIENT (Single Instance)                          │
│                                                          │
│  ┌────────────────────────────────────────────────────┐  │
│  │  defaultOptions (The Global Rulebook)              │  │
│  │  - staleTime: 5 min                                │  │
│  │  - retry: 3                                        │  │
│  └──────────────────────────┬─────────────────────────┘  │
│                             │                            │
│  ┌──────────────────────────▼─────────────────────────┐  │
│  │  QUERY CACHE (The Storage Room)                    │  │
│  │  - ['user', 1] : { data: {...}, status: 'fresh' }  │  │
│  │  - ['posts']   : { data: [...], status: 'stale' }  │  │
│  └────────────────────────────────────────────────────┘  │
└──────────────────────────────────────────────────────────┘

Stale vs. Garbage Collection Timeline

FETCH START
    │
    ▼
[ FRESH ] <─── staleTime (e.g. 1 min)
    │
    ▼
[ STALE ] <─── Still in memory, will refetch on next use
    │
    ▼
[ UNUSED ] <─── All components using this query unmount
    │
    ▼
[ DELETE ] <─── gcTime (e.g. 5 min) ──► PURGED FROM MEMORY

Devtools Interface Concept

┌──────────────────────────────────────────────────────────┐
│ VUE QUERY DEVTOOLS                                     X │
├──────────────────────────────────────────────────────────┤
│ QUERIES (3)                                 [Filter...]  │
│ 🟢 ['profile'] (fresh)                                   │
│ 🟡 ['posts']   (stale)  [Refetch] [Invalidate]           │
│ 🔵 ['settings'] (fetching)                               │
├──────────────────────────────────────────────────────────┤
│ DATA EXPLORER                                            │
│ { "id": 123, "title": "Setup Vue Query", ... }           │
└──────────────────────────────────────────────────────────┘

Summary

ItemValue
Core InstanceQueryClient
RegistrationVueQueryPlugin
Key OptionstaleTime (Freshness duration)
Memory OptiongcTime (Purge delay)
Resilienceretry (Failed request handling)
VisibilityVueQueryDevtools
Injectionprovide/inject under the hood
Env CheckDevtools auto-remove in production

Key takeaways:

  • The QueryClient is the brain of the app. It stores the cache and manages the lifecycle of every request. You should create one instance and pass it to the plugin .
  • Global defaults save time. By setting staleTime and retry logic in the client constructor, you ensure a consistent experience without repeating code in components .
  • staleTime is about cache reuse. It tells the client: “Don’t bother fetching this again if I have a copy that is less than X minutes old.” This is the primary tool for reducing network load .
  • gcTime is about memory management. It defines how long the data stays in the cache “just in case” the user returns to that page, before eventually deleting it to save RAM .
  • The Devtools are your X-ray. They provide a graphical view of the cache, allowing you to see query keys, data, and statuses, which is essential for debugging asynchronous flows .
  • Persistence is possible. For applications that need to survive a page refresh, you can extend the setup to sync the QueryClient cache with LocalStorage .

Remember: Setup is not a “one and done” task; it is the process of defining the performance and resilience rules of your application. Start with a sensible staleTime (like 1 to 5 minutes) and always use the Devtools to verify that your data is fetching exactly when you expect it to.

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!