Web / TanStack Interview Questions
How do you prefetch data in TanStack Query to speed up navigation?
Prefetching loads data into the cache before it is needed — on hover, on route entry, or alongside the current page. When the user navigates, data is already cached and renders instantly.
<script setup lang="ts">
import { useQueryClient } from "@tanstack/vue-query"
import { ref, watchEffect } from "vue"
const qc = useQueryClient()
// Prefetch on hover
async function prefetchPost(id:number){
await qc.prefetchQuery({
queryKey: ["post",id],
queryFn: ()=>fetchPost(id),
staleTime: 1000*60, // skip if cached < 1 min
})
}
// Prefetch next page while user reads current
const page=ref(1)
watchEffect(()=>{
qc.prefetchQuery({
queryKey: ["posts",page.value+1],
queryFn: ()=>fetchPosts(page.value+1),
})
})
</script>
<template>
<RouterLink v-for="p in data?.items" :key="p.id"
:to="`/posts/${p.id}`"
@mouseenter="prefetchPost(p.id)">{{ p.title }}</RouterLink>
</template>
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
