| | |

Vue Query 01 ⚡ Introduction & Server State — Separating client state (Pinia) from async server state and why onMounted + fetch falls short

⏱️ Estimated read: 13 min | |

For years, the standard pattern for data fetching in Vue involved a predictable ritual: define a reactive object or a few refs for data, loading, and error states, and then trigger a fetch or axios call inside the onMounted lifecycle hook. While this approach works for simple prototypes, it quickly becomes a maintenance nightmare as applications scale. This pattern treats server data as just another piece of local state, ignoring the fundamental truth that data living on a server is “out of your control.” It is asynchronous, it can be modified by other users, and it requires sophisticated strategies for caching, invalidation, and synchronization.

Vue Query (part of the TanStack Query family) represents a paradigm shift in how we handle remote data. It is not a replacement for fetch or axios; rather, it is an “async state manager.” It sits between your application and your data source, providing a declarative layer that handles the complexities of caching, background refetching, and state transitions. By adopting Vue Query, you move away from the “imperative” fetching model (telling the app when and how to fetch) to a “declarative” model (telling the app what data it needs and letting the library manage the lifecycle).

A critical part of this transition is understanding the separation of concerns between Client State and Server State. While Pinia is the gold standard for managing Client State—data that exists locally like UI toggles, form inputs, or shopping cart selections—it is often misused as a cache for Server State. Vue Query exists to take that burden away from Pinia, providing a specialized toolset for data that originates from a remote source. This chapter explores the theoretical and practical foundations of Vue Query, highlighting why traditional fetching patterns fail and how to correctly architect your application’s state.

Key point: Server State is fundamentally different from Client State because it is remote, asynchronous, and potentially stale; Vue Query manages these complexities through a “stale-while-revalidate” caching strategy, freeing Pinia to handle strictly local UI state.


Why exists

The Cache Invalidation problem.
When you fetch data and store it in a local variable or a Pinia store, that data is static. If another user updates that data on the server, your local copy becomes “stale.” Manually tracking when to refetch data is complex and error-prone. Vue Query exists to automate this by providing “smart caching” that knows exactly when to background-refresh data based on window focus, network reconnection, or custom time intervals.

The Request Deduplication problem.
In a large application, multiple components might need the same piece of data (e.g., the current user’s profile). Without a dedicated manager, each component might trigger its own onMounted fetch, leading to redundant network requests. Vue Query deduplicates these requests; if five components request the same key at the same time, only one network call is made, and the result is shared across all five.

The Loading/Error Boilerplate problem.
Every manual fetch requires repeating the same logic: isLoading.value = true; try { ... } catch (e) { error.value = e } finally { isLoading.value = false }. This “boilerplate” clutters components and makes them harder to read. Vue Query provides these states out-of-the-box as reactive variables, allowing you to focus on the UI rather than the state machine of the request.

The Background Refresh problem.
Users expect modern web apps to feel “live.” Traditional fetching only happens when a component mounts. Vue Query introduces the concept of “revalidation on focus.” If a user leaves your tab to check an email and returns, Vue Query can automatically check if the data has changed, ensuring the user is always looking at the most current information without a manual page refresh.

The Memory Management problem.
Storing every API response in a global Pinia store leads to “memory bloat.” Over time, the store grows with data the user might never look at again. Vue Query manages a “garbage collection” system for your cache; if a piece of data isn’t used by any component for a specified amount of time (the gcTime), it is automatically evicted from memory.

The “Stale-While-Revalidate” problem.
Users hate waiting for spinners. Vue Query implements the SWR pattern: it immediately shows the “stale” data from the cache while simultaneously fetching a fresh copy in the background. Once the fresh data arrives, the UI updates smoothly. This makes the application feel significantly faster and more responsive than a traditional “show spinner -> wait -> show data” flow.


a. The Failure of the onMounted + fetch Pattern

To understand why Vue Query is necessary, we must first analyze the common “imperative” pattern and its inherent flaws. Consider a component that fetches a list of products.

<script setup>
import { ref, onMounted } from 'vue'

const products = ref([])
const isLoading = ref(false)
const error = ref(null)

const loadProducts = async () => {
  isLoading.value = true
  try {
    const res = await fetch('https://api.example.com/products')
    products.value = await res.json()
  } catch (e) {
    error.value = 'Failed to load'
  } finally {
    isLoading.value = false
  }
}

onMounted(loadProducts)
</script>

<template>
  <div v-if="isLoading">Loading...</div>
  <ul v-else>
    <li v-for="p in products" :key="p.id">{{ p.name }}</li>
  </ul>
</template>

The problems with this approach are subtle but significant. First, there is no caching. If the user navigates away and back, the entire fetch repeats, and the user sees a loading spinner again. Second, there is no sharing. If another component on the same page needs the same product list, it will trigger a second network request. Third, there is no automatic retry. If the network blips, the fetch simply fails, and the user is stuck with an error unless they refresh the page.

Finally, this pattern makes state synchronization difficult. If you update a product in a different component, you have no easy way to tell this specific component to “refresh its data.” You would have to resort to event buses, complex Pinia logic, or global “refresh” triggers, all of which add fragility to the codebase.


b. Client State (Pinia) vs. Server State (Vue Query)

Architecting a modern Vue app requires a clear distinction between two types of state. Mixing them in a single tool (like Pinia) often leads to “Store Bloat,” where your Pinia stores become thousands of lines long, filled with loading flags and API service calls.

Client State (Pinia’s Territory):
This is data that is owned by the application and is strictly local. It is synchronous and easy to manage.

  • Is the sidebar open?
  • What theme is the user using (dark/light)?
  • Is the user currently typing in a search bar?
  • What items are in the shopping cart (before checkout)?

Server State (Vue Query’s Territory):
This is data that is owned by the server. It is asynchronous, shared with other users, and can be changed without your app’s knowledge.

  • The list of products in the database.
  • The user’s profile information.
  • Comments on a blog post.
  • Search results from an API.

By offloading Server State to Vue Query, your Pinia stores become significantly smaller and easier to manage. You no longer need to write actions like fetchUsers() in Pinia; instead, you define a Query. Pinia is left to do what it does best: managing the local UI state and complex client-side business logic.


c. Setup and the useQuery Hook

Integrating Vue Query starts with installing the plugin. This establishes the QueryClient, which acts as the “brain” and the central cache storage for your entire application.

// main.ts
import { createApp } from 'vue'
import { VueQueryPlugin } from '@tanstack/vue-query'
import App from './App.vue'

const app = createApp(App)

// Provide the QueryClient to the app
app.use(VueQueryPlugin)
app.mount('#app')

The primary tool for fetching data is the useQuery hook. It requires two main inputs: a Query Key (a unique identifier for the data) and a Query Function (an async function that returns the data).

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

// Vue Query handles the lifecycle automatically
const { data, isLoading, isError, error } = useQuery({
  queryKey: ['products'],
  queryFn: async () => {
    const res = await fetch('https://api.example.com/products')
    if (!res.ok) throw new Error('Network error')
    return res.json()
  },
})
</script>

<template>
  <div v-if="isLoading">Loading products...</div>
  <div v-else-if="isError">Error: {{ error.message }}</div>
  <ul v-else>
    <li v-for="product in data" :key="product.id">
      {{ product.name }}
    </li>
  </ul>
</template>

In this declarative approach, we don’t tell Vue Query when to fetch. We tell it: “I need the data associated with the key ['products'], and here is how you get it.” Vue Query then checks its cache. If the data is there and not “stale,” it returns it immediately. If it’s stale, it returns the cached data but fetches a fresh copy in the background. If it’s missing, it shows the isLoading state.


Complete Example Session

// ============================================
// PART 1: PLUGIN INSTALLATION
// ============================================
import { VueQueryPlugin, QueryClient } from '@tanstack/vue-query'
const queryClient = new QueryClient()
app.use(VueQueryPlugin, { queryClient })

// ============================================
// PART 2: DEFINING A BASIC QUERY
// ============================================
const { data, status } = useQuery({
  queryKey: ['todos'],
  queryFn: fetchTodos
})

// ============================================
// PART 3: USING DYNAMIC KEYS
// ============================================
// When userId.value changes, the query refetches automatically
const userId = ref(1)
const { data: user } = useQuery({
  queryKey: ['user', userId],
  queryFn: () => fetchUser(userId.value)
})

// ============================================
// PART 4: HANDLING ERROR STATES
// ============================================
const { isError, error } = useQuery({
  queryKey: ['posts'],
  queryFn: fetchPosts,
  retry: 3 // Automatic retries on failure
})

// ============================================
// PART 5: REFRESHING DATA MANUALLY
// ============================================
const { refetch } = useQuery({
  queryKey: ['profile'],
  queryFn: fetchProfile
})
// Call refetch() on button click

// ============================================
// PART 6: STALE TIME CONFIGURATION
// ============================================
const { data: config } = useQuery({
  queryKey: ['config'],
  queryFn: fetchConfig,
  staleTime: 1000 * 60 * 5 // Consider data fresh for 5 minutes
})

// ============================================
// PART 7: QUERY STATUS VS FETCH STATUS
// ============================================
// isLoading = No data yet
// isFetching = Request is in-flight (could be background)
const { isLoading, isFetching } = useQuery({ queryKey: ['x'], queryFn: fetchX })

// ============================================
// PART 8: DEPENDENT QUERIES
// ============================================
// Only run the second query if the first has data
const { data: userEmail } = useQuery({ queryKey: ['user'], queryFn: getUser })
const { data: projects } = useQuery({
  queryKey: ['projects', userEmail],
  queryFn: () => getProjects(userEmail.value),
  enabled: computed(() => !!userEmail.value)
})

// ============================================
// PART 9: INITIAL DATA (PLACEHOLDER)
// ============================================
const { data: list } = useQuery({
  queryKey: ['items'],
  queryFn: fetchItems,
  initialData: [] // UI doesn't break if data is missing
})

// ============================================
// PART 10: GARBAGE COLLECTION
// ============================================
const { data: temp } = useQuery({
  queryKey: ['temp'],
  queryFn: fetchTemp,
  gcTime: 1000 * 10 // Remove from cache 10s after unmount
})

The parts above cover the transition from plugin setup to complex query patterns, including dynamic keys, retry logic, and cache timing.


Quick Reference

useQuery Return Properties

PropertyTypeDescription
dataTThe successfully fetched data
isLoadingBooleanTrue if first fetch is in progress
isFetchingBooleanTrue if any fetch is in progress
isErrorBooleanTrue if the query failed
errorErrorThe error object if isError is true
refetchFunctionManually trigger a refresh

Important Configuration Options

OptionDefaultDescription
staleTime0Time in ms before data is considered “old”
gcTime5 minTime in ms before unused data is deleted
retry3Number of times to retry on failure
enabledtrueSet to false to disable automatic fetching
refetchOnWindowFocustrueRefetch when browser tab is re-entered

Query Statuses

StatusMeaning
pendingNo data in cache, first fetch hasn’t finished
errorRequest failed
successRequest succeeded and data is available

Best Practices

✅ Do This:

// Define query keys as arrays for consistency
queryKey: ['user', userId]                                     // ✅

// Handle errors inside the query function (throw them)
queryFn: async () => { if(!res.ok) throw new Error(); }        // ✅

// Use `staleTime` for data that doesn't change often
staleTime: 60000                                               // ✅

// Separate fetching logic into a services/api file
queryFn: () => userService.getProfile()                        // ✅

❌ Don’t Do This:

// Don't use Vue Query for simple local UI state (use Pinia)
const { data: isModalOpen } = useQuery(...)                    // ❌

// Don't use standard fetch without error checking in queryFn
queryFn: () => fetch('/api').then(res => res.json())           // ❌

// Don't put query logic inside a `watch` effect manually
// (useQuery is already reactive to its keys)                  // ❌

// Don't use a string as a queryKey (always use an array)
queryKey: 'users'                                              // ❌

Common Pitfalls

PitfallWhy It HappensFix
No re-fetch on ID changeKey was ['user'] instead of ['user', id]Include dependencies in the queryKey
Infinite LoopqueryFn modifies a state used in queryKeyKeep query functions pure; only return data
Data is Always StaleDefault staleTime is 0Set a higher staleTime for non-realtime data
Error not caughtfetch doesn’t throw on 404/500Manually throw if !response.ok
Multiple spinnersUsing isFetching instead of isLoadingUse isLoading for the initial loading state only
Missing PluginForgot app.use(VueQueryPlugin)Register the plugin in main.ts

Real-World Examples

1. Global User Profile

const { data: user } = useQuery({ queryKey: ['profile'], queryFn: getProfile });

2. Search with Debounce (Key reactivity)

const { data } = useQuery({ queryKey: ['search', searchTerm], queryFn: () => api.search(searchTerm.value) });

3. Polling for Live Status

useQuery({ queryKey: ['status'], queryFn: getStatus, refetchInterval: 5000 });

4. Disabling a query until a condition is met

useQuery({ queryKey: ['data'], queryFn: fetcher, enabled: isReady });

5. Dashboard with long-lived Cache

useQuery({ queryKey: ['stats'], queryFn: getStats, staleTime: Infinity });

6. Selective Retries

retry: (failureCount, error) => error.status !== 404

7. Mocking Initial Data from LocalStorage

initialData: () => JSON.parse(localStorage.getItem('cache'))

8. Network-only Fetch (No Cache)

staleTime: 0, gcTime: 0

9. Query based on Route Params

const route = useRoute();
useQuery({ queryKey: ['item', route.params.id], queryFn: () => getItem(route.params.id) });

10. Fetching Config on App Start

const { data } = useQuery({ queryKey: ['config'], queryFn: fetchConfig, staleTime: 24 * 60 * 60 * 1000 });

Visual

The Cache Lifecycle

┌──────────────────────────────────────────────────────────┐
│  USER NAVIGATES TO PAGE                                  │
├──────────────────────────────────────────────────────────┤
│ 1. Check Query Key ['user', 1] in Cache                  │
│                                                          │
│  MISS? ────► Show Spinner ────► Fetch ────► Store/Show   │
│                                                          │
│  HIT?  ────► Show Cache ───┬──► IS STALE? ──► BACKGROUND │
│                            │                  FETCH      │
│                            └──► IS FRESH? ──► DO NOTHING │
└────────────────────────────┴─────────────────────────────┘

Deduplication Mechanism

┌──────────────────┐      ┌──────────────────┐
│   Component A    │      │   Component B    │
│ useQuery(['api'])│      │ useQuery(['api'])│
└────────┬─────────┘      └────────┬─────────┘
         │                         │
         └────────────┬────────────┘
                      ▼
             ┌──────────────────┐
             │   QUERY CLIENT   │
             │ (Single Request) │
             └────────┬─────────┘
                      ▼
             ┌──────────────────┐
             │      SERVER      │
             └──────────────────┘

Client vs. Server State

┌──────────────────────────────┐  ┌──────────────────────────────┐
│       PINIA (CLIENT)         │  │     VUE QUERY (SERVER)       │
├──────────────────────────────┤  ├──────────────────────────────┤
│  - Form Data                 │  │  - API Responses             │
│  - UI Toggles                │  │  - Database Records          │
│  - Navigation State          │  │  - User Profiles             │
│                              │  │                              │
│  [ OWNED BY BROWSER ]        │  │  [ OWNED BY REMOTE SERVER ]  │
└──────────────────────────────┘  └──────────────────────────────┘

Summary

ItemValue
PurposeManaging asynchronous Server State
Core HookuseQuery
Requirement 1Unique Query Key (Array)
Requirement 2Async Query Function
State LogicSWR (Stale-While-Revalidate)
CachingAutomatic, configurable via staleTime
Client StateStill managed by Pinia
DeduplicationBuilt-in for overlapping requests

Key takeaways:

  • Server state is different from client state. Remote data is asynchronous, shared, and can become stale; treating it like a local variable leads to complexity and bugs .
  • Vue Query is an async state manager. It handles the “middle layer” of data fetching, including caching, background updates, and state transitions (loading/error) .
  • The onMounted pattern is insufficient. It lacks caching, deduplication, and the ability to background-refresh, often resulting in a poor user experience with too many spinners .
  • Keys and Functions are the core inputs. Every query needs a unique array key (for caching) and an async function (for the actual network call) .
  • Stale-While-Revalidate improves performance. Vue Query shows cached data immediately while fetching updates in the background, making the UI feel instantaneous .
  • It reduces Pinia bloat. By offloading API responses to Vue Query, Pinia is reserved for strictly local UI logic and state that the app truly owns .

Remember: Stop treating your server data as if it lives in your browser. Data from an API is a snapshot of a remote resource that is constantly changing. Vue Query provides the tools to manage that snapshot gracefully, ensuring your users always have the fastest and most accurate view of your data without the manual boilerplate of traditional fetching.

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!