TanStack Query for Vue
Replace hand-rolled fetching with @tanstack/vue-query v5 — reactive query keys, caching, mutations, invalidation — and split state between it and Pinia.
TanStack Query for Vue
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- @tanstack/vue-query is installed with app.use(VueQueryPlugin) and gives every component access to one shared query cache, keyed by queryKey.
- useQuery returns refs (data, error, isPending, isFetching and more), and refs or getters placed in queryKey are tracked, so the query refetches when they change.
- Passing a ref's .value or a prop's value into queryKey loses reactivity; pass the ref itself or a getter such as () => props.id.
- staleTime decides how long cached data counts as fresh, and gcTime how long unused data stays in memory; the defaults are 0 and five minutes.
- useMutation sends writes, and queryClient.invalidateQueries marks matching cached queries stale so the UI refetches fresh data after a change.
- Server state goes in the query cache and client state stays in Pinia; Pinia Colada, from Pinia's author, is a Pinia-based alternative with the same model.
From a composable to a cache
The previous lesson ended with the useFetch composable’s limits: every call fetches on its own, nothing is shared, and nothing refetches when the data may have changed. The fix is to move the data out of each component into one shared cache, keyed by what was requested, that knows how old each entry is.
That is what TanStack Query does. Its core is framework-agnostic, with thin adapters for React, Vue, Solid, Svelte, and Angular. The Vue adapter is @tanstack/vue-query, currently on major version 5. The general argument for a query cache is made in React’s the case for a data-fetching library, and the cache’s timing rules in TanStack Query fundamentals. Both carry over to Vue unchanged. This lesson focuses on what the Vue adapter does differently: it speaks refs.
Installing
npm install @tanstack/vue-query
// main.js
import { createApp } from 'vue'
import { VueQueryPlugin } from '@tanstack/vue-query'
import App from './App.vue'
createApp(App).use(VueQueryPlugin).mount('#app')
VueQueryPlugin creates a QueryClient, the object that owns the cache, and provides it to every component. You can pass your own with app.use(VueQueryPlugin, { queryClient }) to set app-wide defaults.
Your first query
<script setup>
import { useQuery } from '@tanstack/vue-query'
async function fetchPosts() {
const res = await fetch('/api/posts')
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return res.json()
}
const { data: posts, error, isPending, isFetching } = useQuery({
queryKey: ['posts'],
queryFn: fetchPosts,
})
</script>
<template>
<p v-if="isPending">Loading…</p>
<p v-else-if="error">Couldn't load posts: {{ error.message }}</p>
<template v-else>
<small v-if="isFetching">Refreshing…</small>
<ul>
<li v-for="post in posts" :key="post.id">{{ post.title }}</li>
</ul>
</template>
</template>
Compare this with the hand-rolled version. The three refs and the try/catch are gone. useQuery takes a v5-style options object, calls queryFn, and stores the result under queryKey. Everything it returns is a ref, so it destructures safely and unwraps in the template.
Two flags replace the single loading ref, because there are now two situations. isPending means there is no data yet. isFetching means a request is in flight, which also happens in the background while cached data is already on screen.
Any other component that calls useQuery with ['posts'] reads the same cache entry. If two mount at once, one request goes out. If you leave the page and come back within five minutes, the cached list renders instantly while a background refetch checks for changes.
Reactive keys: the Vue-specific part
This is where Vue Query differs from its React sibling. React re-runs your component on every render, so a changed key is picked up automatically. Vue’s setup runs once, so Vue Query has to track the key, and it can only track what you hand it as a ref or a getter.
// Wrong: reads the value once and never refetches
useQuery({
queryKey: ['user', userId.value],
queryFn: () => getUser(userId.value),
})
// Right: the ref itself goes in the key
useQuery({
queryKey: ['user', userId],
queryFn: () => getUser(userId.value),
})
Props follow the same rule. props.userId read directly is a plain value; wrap it in a getter:
const props = defineProps({ userId: String })
const { data: user } = useQuery({
queryKey: ['user', () => props.userId],
queryFn: () => getUser(props.userId),
enabled: () => !!props.userId, // don't fetch until there is an id
})
Vue Query’s docs recommend writing query composables that accept a MaybeRefOrGetter, putting the argument straight into the key, and reading it with toValue inside queryFn:
import { toValue } from 'vue'
export function useUser(userId) {
return useQuery({
queryKey: ['user', userId],
queryFn: ({ signal }) =>
fetch(`/api/users/${toValue(userId)}`, { signal }).then((r) => r.json()),
})
}
Callers can then pass a string, a ref, or () => props.userId. Note signal: Vue Query hands queryFn an AbortSignal, which cancels the request when it’s no longer needed. That is the race-condition fix from the last lesson, built in.
Getters are only resolved in queryKey and enabled. Other options accept refs.
Freshness: staleTime and gcTime
Two clocks control the cache, the same as in every TanStack adapter:
staleTime(default0): how long data counts as fresh. Fresh data is served with no request at all. Stale data is still shown immediately, but triggers a background refetch when a component mounts, the window regains focus, or the network reconnects.gcTime(default five minutes): how long an entry nobody is using stays in memory before it’s discarded.
Failed queries are retried three times by default before error is set. For data that rarely changes, raise staleTime: staleTime: 5 * 60_000.
Writing data: mutations and invalidation
Reads go through useQuery; writes go through useMutation. After a write succeeds, you tell the cache which queries are now out of date:
import { useMutation, useQueryClient } from '@tanstack/vue-query'
const queryClient = useQueryClient()
const { mutate: addPost, isPending: saving } = useMutation({
mutationFn: (post) =>
fetch('/api/posts', { method: 'POST', body: JSON.stringify(post) }),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['posts'] })
},
})
invalidateQueries matches by prefix, so ['posts'] covers ['posts'], ['posts', 7], and ['posts', { page: 2 }]. Matching queries are marked stale, and the ones currently on screen refetch.
One consequence of a shared cache: query results are treated as immutable. Don’t bind data to v-model or edit it in place. Copy it into a local ref for an edit form and send the change through a mutation.
Who owns what: Pinia and the query cache
With a query cache in place, the split from when you need a store becomes concrete:
- Query cache: anything that comes from the server. Users, posts, orders, search results.
- Pinia: state the browser owns. The cart before checkout, UI preferences, a wizard’s in-progress answers, the current filter selection.
The two meet naturally. A Pinia store can hold the selected filters, and a query can use them as its key: queryKey: ['products', () => filters.category]. Change the filter in the store and the query refetches on its own. What you should no longer do is fetch in a Pinia action and copy the response into store state; that rebuilds a cache with none of the freshness rules.
Pinia Colada, the other option
Vue has a second library built on the same idea. Pinia Colada (@pinia/colada), by Pinia’s author Eduardo San Martin Morote, reached 1.0 in March 2026. It is built on Pinia, its query cache is itself a Pinia store, and its API is close to TanStack’s with different names: useQuery({ key, query }), useMutation({ mutation }), and useQueryCache() for invalidation. It is a credible choice, but it is not an official recommendation: neither the Vue docs nor the Pinia docs name a data-fetching library. Choose TanStack Query for its larger ecosystem and cross-framework knowledge, or Pinia Colada for a smaller, Vue-only library that fits with Pinia. The concepts in this lesson carry over directly either way.
What the video covers
Maya Shavin’s talk at Vue.js Israel is about architecture rather than API: how to structure an app’s state across Pinia and TanStack Query, so that each library holds the kind of state it is built for. That is the question this lesson closes on. It is a meetup recording, not a step-by-step tutorial, so the API sections above carry the mechanics: installing the plugin, reactive keys, staleTime and gcTime, mutations, and invalidation. The three-minute Vue School clip by the same speaker, in the links below, is a quick API taste. Eduardo San Martin Morote’s talk shows the same model through Pinia Colada.
Where this fits
This closes the state-and-data group. Server rendering changes how data gets to the page; data fetching in Nuxt covers Nuxt’s useFetch and useAsyncData.
Check yourself
A composable calls useQuery({ queryKey: ['user', userId.value], queryFn: () => getUser(userId.value) }). When userId changes, nothing refetches. Why?
userId.value is read once when the composable runs, so the key contains a plain value that Vue Query cannot track. Put the ref itself in the key, ['user', userId], or a getter, and read the current value inside queryFn with toValue(userId). Vue Query then sees the key change and fetches the new user.
What is the difference between isPending and isFetching?
isPending is true while the query has no data yet, such as the very first load. isFetching is true whenever a request is in flight, including background refetches when cached data is already on screen. A good UI shows a full loading state for isPending and at most a small indicator for isFetching.
After a useMutation call adds a todo, the todo list still shows the old data. What is the usual fix?
In the mutation's onSuccess, call queryClient.invalidateQueries({ queryKey: ['todos'] }). This marks every query whose key starts with 'todos' as stale and refetches the ones currently on screen, so the list picks up the new item from the server.
Why can't you bind data from useQuery directly to a v-model on an edit form?
Query results are treated as immutable cache entries that other components may be sharing. Editing them in place would change the cache behind Vue Query's back. Copy the data into a local ref for the form, then send the edit with a mutation and invalidate or update the query.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.