| | |

Vue Query 03 ⚡ useQuery Fundamentals — Query Keys, Query Functions, and Result Handling

⏱️ Estimated read: 13 min | |

The useQuery hook is the primary tool for fetching and managing server state in a Vue application. While the installation of the plugin provides the infrastructure, useQuery is the actual interface used within components to declare a data dependency. Unlike traditional imperative fetching where you write code to “go get the data,” useQuery is declarative: you describe what the data is (the Query Key) and how to get it (the Query Function), and the library manages the complexity of the request lifecycle, caching, and reactivity for you.

At its core, useQuery is a state machine. It transitions through a series of predictable statuses based on the success or failure of the network request and the state of the cache. For developers, this means no longer having to manually create ref(false) for loading states or ref(null) for error objects. The hook returns a reactive object containing everything needed to render a robust UI, including the data itself, various status flags, and utility functions for manual control. Understanding these fundamentals is the difference between a application that merely “works” and one that provides a seamless, professional user experience.

This chapter dives deep into the two mandatory pillars of a query: the Query Key and the Query Function. We will explore how keys act as the primary identifiers for the cache and how the query function must behave to ensure errors are handled correctly. We will also dissect the reactive result object, focusing on the nuanced differences between “pending,” “fetching,” and “error” states to help you build interfaces that never leave the user guessing.

Key point: Every useQuery instance requires a unique array-based Query Key for identification and an asynchronous Query Function that returns a Promise; the hook then provides reactive flags like isPending and isError to manage the UI state.


Why exists

The Cache Identification problem.
In a global cache, there must be a way to distinguish between “User #1” and “User #2.” Without a consistent naming convention, data would overwrite itself. Query Keys exist as a unique addressing system. Because they are arrays, they allow for hierarchical organization, ensuring that when data for a specific ID changes, it doesn’t affect other unrelated cached data.

The Automatic Dependency problem.
When a user changes a filter or a page number, the data needs to refresh. In standard Vue, you would have to watch a variable and manually call a fetch function. Query Keys solve this by acting as dependencies. If a reactive value is included in the Query Key array, Vue Query automatically triggers a refetch whenever that value changes, making synchronization automatic and declarative.

The State Machine complexity problem.
Handling every possible state of a network request is difficult. What if the data is in the cache but currently updating? What if the first request failed, but we are retrying? These edge cases result in complex “if/else” logic in components. The reactive flags like isPending and isFetching exist to provide a standardized state machine, allowing the UI to react to the granular details of the request lifecycle.

The Error Propagation problem.
The browser’s native fetch API is notoriously silent about HTTP errors like 404 or 500; it only throws if the network itself fails. This leads to apps that show “success” for empty data when a server error actually occurred. Query Functions in Vue Query exist to enforce a “Promise-based” contract: if the function throws or returns a rejected promise, the library officially recognizes an error state, triggering retries and updating the isError flag.

The Deduplication logic problem.
If two components on a page both request the same data, they shouldn’t trigger two network calls. Vue Query uses the Query Key to recognize these overlaps. By checking the key before executing the Query Function, the library can “deduplicate” the request, letting the second component wait for the first request’s result, saving bandwidth and server resources.

The UI Performance problem.
Showing a blank screen or a spinner every time a user navigates back to a page is jarring. The result handling logic in useQuery exists to support the “Stale-While-Revalidate” pattern. It allows the component to access the data from the cache immediately while the status flags indicate that a background update is happening, providing a much smoother and faster user experience.


a. The Query Key: Identification and Dependencies

The Query Key is the most important part of useQuery. It is an array of values that uniquely identifies the data in the cache. Vue Query serializes this array into a string internally to use as a lookup key. While you can use simple strings, arrays are the standard because they can contain dynamic information like IDs, categories, or sort orders.

// A simple, static key
const { data } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos })

// A hierarchical key with an ID
const { data: todo } = useQuery({ 
  queryKey: ['todos', 5], 
  queryFn: () => fetchTodoById(5) 
})

// A complex key with a filter object
const { data: list } = useQuery({ 
  queryKey: ['todos', { status: 'done', page: 1 }], 
  queryFn: fetchFilteredTodos 
})

The order of items in the array matters. ['todos', 5] is not the same as [5, 'todos']. However, objects inside the array are checked for “deep equality,” meaning ['todos', { a: 1, b: 2 }] is considered identical to ['todos', { b: 2, a: 1 }].

One of the most powerful features of Query Keys is their role as reactive dependencies. If you include a ref or a computed value in the key, Vue Query will watch that value. When it changes, the key changes, the cache lookup fails (because it’s a “new” key), and a refetch is automatically triggered.

<script setup>
const userId = ref(1)

const { data } = useQuery({
  // When userId.value changes, this query re-runs!
  queryKey: ['user', userId],
  queryFn: () => fetchUser(userId.value)
})
</script>

b. The Query Function: Data Retrieval and Errors

The Query Function (queryFn) is an asynchronous function that must return a Promise. This function is where the actual network request (using fetch, axios, or any other library) takes place. The promise should either resolve with the data or throw an error.

A critical detail when using the native fetch API: it does not throw an error for status codes like 404 or 500. It only throws if there is a network failure or if the request is blocked. To make Vue Query’s error handling work correctly, you must manually check the response status and throw an error yourself.

const { data, error, isError } = useQuery({
  queryKey: ['posts'],
  queryFn: async () => {
    const response = await fetch('/api/posts')
  
    // Manual error check is REQUIRED for native fetch
    if (!response.ok) {
      throw new Error('Server responded with an error')
    }
  
    return response.json()
  }
})

The Query Function receives a QueryFunctionContext object as an argument. This object contains the queryKey, which can be useful if you want to write a generic fetching function that extracts the ID directly from the key.

const fetchItem = async ({ queryKey }) => {
  const [_key, id] = queryKey // Desctructure ['items', 5]
  const res = await fetch(`/api/items/${id}`)
  return res.json()
}

// In component
useQuery({ queryKey: ['items', 5], queryFn: fetchItem })

c. Handling Result States: Pending, Fetching, and Error

useQuery returns a reactive object that describes the current state of the query. In TanStack Query v5, the terminology changed slightly to be more precise. The three main flags you will use are isPending, isFetching, and isError.

  1. isPending: This means the query has no data in the cache and is currently performing its initial fetch. This is when you usually show a full-page spinner or skeleton screens.
  2. isFetching: This is a more general flag. It is true whenever a request is in-flight, including background refetches. You might use this to show a small loading indicator in the corner of the UI while keeping the old data visible.
  3. isError: This becomes true if the query function throws an error. When this is true, the error object becomes available, containing the details of the failure.
<template>
  <!-- isPending: No data yet, first load -->
  <div v-if="isPending">
    <SkeletonLoader />
  </div>

  <!-- isError: Something went wrong -->
  <div v-else-if="isError">
    <p>Error: {{ error.message }}</p>
    <button @click="refetch">Retry</button>
  </div>

  <!-- success: We have data -->
  <div v-else>
    <ul>
      <li v-for="item in data" :key="item.id">{{ item.title }}</li>
    </ul>
  
    <!-- isFetching: Background update is happening -->
    <small v-if="isFetching">Updating in background...</small>
  </div>
</template>

The data property holds the result of the successful query. Because of the “Stale-While-Revalidate” logic, data might contain “old” information from the cache while isFetching is true. This is a feature, not a bug—it allows your UI to remain interactive and populated while the latest updates are retrieved.


Complete Example Session

// ============================================
// PART 1: THE IMPORTS
// ============================================
import { useQuery } from '@tanstack/vue-query'
import { ref, computed } from 'vue'

// ============================================
// PART 2: DYNAMIC STATE
// ============================================
const postId = ref(1)

// ============================================
// PART 3: THE QUERY DEFINITION
// ============================================
const { 
  data, 
  isPending, 
  isFetching, 
  isError, 
  error, 
  refetch 
} = useQuery({
  // PART 4: REACTIVE QUERY KEY
  queryKey: ['post', postId],

  // PART 5: THE QUERY FUNCTION
  queryFn: async () => {
    const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${postId.value}`)
    if (!res.ok) throw new Error('Post not found')
    return res.json()
  },

  // PART 6: CONFIGURATION (Optional)
  retry: 2,
  staleTime: 1000 * 30
})

// ============================================
// PART 7: LOGGING STATES
// ============================================
// console.log('Current Data:', data.value)
// console.log('Is Loading for the first time?', isPending.value)
// console.log('Is any network call happening?', isFetching.value)

// ============================================
// PART 8: TRIGGERING REFETCH
// ============================================
const manualRefresh = () => refetch()

// ============================================
// PART 9: UPDATING DEPENDENCIES
// ============================================
const nextPost = () => {
  postId.value++ // This automatically triggers the query above
}

// ============================================
// PART 10: DERIVED STATE
// ============================================
const postTitle = computed(() => data.value?.title || 'No Title')

The parts above cover a standard implementation of useQuery, demonstrating how reactive keys, error-aware functions, and status flags work together to create a dynamic data-fetching system.


Quick Reference

The useQuery Result Object

PropertyTypeDescription
dataTThe actual data returned from the function
isPendingBooleanTrue if first fetch is active and no data exists
isFetchingBooleanTrue if any network request is active
isErrorBooleanTrue if the last fetch failed
errorErrorThe error object thrown by the queryFn
statusString'pending', 'error', or 'success'
refetchFunctionFunction to manually trigger a fetch

Query Key Syntax

TypeExampleUse Case
Simple['posts']Global list, no filters
Parametric['posts', 1]Specific resource by ID
Filtered['posts', { sort: 'asc' }]Lists with search/sort params
Nested['user', 1, 'comments']Child resources

Status vs. FetchStatus (V5)

statusfetchStatusUI Meaning
pendingfetchingInitial hard load (no data)
successfetchingBackground refresh (has old data)
successidleIdle state (has data, not fetching)
erroridleFailed state

Best Practices

✅ Do This:

// Use an array for ALL query keys, even simple ones
queryKey: ['todos']                                            // ✅

// Throw errors in the query function so isError works
if (!res.ok) throw new Error();                                // ✅

// Use isPending for the initial screen-wide loading state
if (isPending) return <BigSpinner />                           // ✅

// Include all variables used in queryFn inside the queryKey
queryKey: ['user', userId]                                     // ✅

❌ Don’t Do This:

// Don't use strings as query keys (they are converted to arrays)
queryKey: 'todos'                                              // ❌

// Don't modify external state inside a queryFn (side effects)
queryFn: () => { myRef.value = 'done'; return fetch(); }       // ❌

// Don't forget to handle the error state in the template
// (Users will just see an empty screen or old data)            // ❌

// Don't use data.value without optional chaining or checks
console.log(data.value.name) // Crash if data is undefined     // ❌

Common Pitfalls

PitfallWhy It HappensFix
No Refetch on ID changeID was not included in the queryKeyAdd the ID variable to the queryKey array
isError is never truefetch doesn’t throw on 404/500Manually throw an error if !res.ok
Infinite LoopqueryFn updates a reactive value in the keyRemove state updates from the queryFn
Data is undefinedQuery hasn’t finished yetUse isPending check or initialData
Stale Data in UIComponent doesn’t react to isFetchingAdd a background loading indicator
Multiple RequestsKeys are slightly different (e.g., ['user', '1'] vs ['user', 1])Ensure key data types are consistent

Real-World Examples

1. Fetching a single user

const { data } = useQuery({ queryKey: ['user', id], queryFn: () => getUser(id) })

2. Search with dynamic keyword

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

3. Automatic page refresh (polling)

const { data } = useQuery({ queryKey: ['stats'], queryFn: getStats, refetchInterval: 3000 })

4. Disabling query until ID is available

const { data } = useQuery({ queryKey: ['x', id], queryFn: getX, enabled: !!id.value })

5. Using Axios (throws automatically)

queryFn: () => axios.get('/api/data').then(res => res.data)

6. Retrying only on specific errors

retry: (count, err) => err.status !== 404 && count < 3

7. Generic fetcher with context

queryFn: ({ queryKey }) => api.get(`/items/${queryKey[1]}`)

8. Sorting a list

const { data } = useQuery({ queryKey: ['posts', { sort: 'desc' }], queryFn: fetchPosts })

9. Showing data from a placeholder

const { data } = useQuery({ queryKey: ['user'], queryFn: getUser, placeholderData: fallbackUser })

10. Manual refresh button

<button @click="refetch()">Reload Data</button>

Visual

The Query Life Cycle

┌──────────────────────────────────────────────────────────┐
│  1. Component Mounts                                     │
├──────────────────────────────────────────────────────────┤
│  2. useQuery(['post', 1]) checks Cache                   │
│                                                          │
│  [ Cache Empty ]                   [ Cache Hit ]         │
│         │                                 │              │
│  isPending = true                 isPending = false      │
│  isFetching = true                isFetching = true      │
│  data = undefined                 data = cached_val      │
│         │                                 │              │
│  (Network Call)                   (Background Call)      │
│         │                                 │              │
│  3. SUCCESS ──────────────────────┘                      │
│     isFetching = false, isPending = false, data = fresh  │
└──────────────────────────────────────────────────────────┘

Query Key Serialization

┌──────────────────────────────────────────────────────────┐
│  ARRAY KEY                       CACHE STRING (Internal) │
├──────────────────────────────────────────────────────────┤
│  ['user', 5]           ──►       '["user",5]'            │
│  ['user', 10]          ──►       '["user",10]'           │
│  ['posts', {a:1, b:2}] ──►       '["posts",{"a":1,"b":2}]'│
└──────────────────────────────────────────────────────────┘

The State Machine (Flags)

┌──────────────────┐      ┌──────────────────┐      ┌──────────────────┐
│     PENDING      │─────►│     SUCCESS      │─────►│    FETCHING      │
│ (First request)  │      │ (Data in cache)  │      │ (Bg Update)      │
├──────────────────┤      ├──────────────────┤      ├──────────────────┤
│ data: undefined  │      │ data: [...]      │      │ data: [stale]    │
│ isPending: true  │      │ isPending: false │      │ isPending: false │
│ isFetching: true │      │ isFetching: false│      │ isFetching: true │
└──────────────────┘      └──────────────────┘      └──────────────────┘

Summary

ItemValue
IdentifierQuery Key (Array)
Data FetcherQuery Function (Async/Promise)
Initial LoadingisPending
Ongoing ActivityisFetching
Failure StateisError
Primary Outputdata
Dependency RoleKeys trigger automatic refetching
ConsistencyObjects in keys are deep-equal

Key takeaways:

  • Query Keys are the unique IDs of your data. Always use an array and include any reactive variable that the query depends on to ensure data stays in sync .
  • The Query Function must handle errors. Native fetch doesn’t throw on HTTP errors (like 404), so you must manually throw to trigger Vue Query’s error state .
  • isPending vs. isFetching. Use isPending for the first-time data load and isFetching to show background updates when data already exists .
  • Data is available even during updates. This “Stale-While-Revalidate” behavior is key to a fast UI; avoid showing a blank screen if cached data is already available .
  • Keys determine deduplication. Two components using the exact same Query Key will share the same network request and cached data .
  • Refetch is your escape hatch. If you need to refresh data outside of the automatic dependency system, the refetch function provides manual control .

Remember: useQuery is a state machine that turns an asynchronous function into a reactive, cached resource. Master the relationship between the Query Key (the ID) and the Query Function (the fetcher), and the library will handle the complex orchestration of loading, errors, and background updates for you.

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!