Web / TanStack Interview Questions
How do you combine useInfiniteQuery with useVirtualizer for an infinitely scrolling virtualised list?
This is one of the most powerful TanStack patterns: useInfiniteQuery fetches pages as the user scrolls while useVirtualizer renders only visible DOM nodes — together they handle millions of rows with minimal memory.
<script setup lang="ts">
import { ref, computed, watchEffect } from "vue"
import { useInfiniteQuery } from "@tanstack/vue-query"
import { useVirtualizer } from "@tanstack/vue-virtual"
const parentRef=ref<HTMLDivElement|null>(null)
const { data, fetchNextPage, hasNextPage, isFetchingNextPage }=useInfiniteQuery({
queryKey: ["posts","infinite"],
queryFn: ({pageParam})=>fetchPosts({page:pageParam}),
initialPageParam: 0,
getNextPageParam: last=>last.nextPage??undefined,
})
const allRows=computed(()=>data.value?data.value.pages.flatMap(p=>p.rows):[])
const virt=useVirtualizer({
// +1 sentinel row triggers next-page fetch when it enters viewport
get count(){ return hasNextPage.value?allRows.value.length+1:allRows.value.length },
getScrollElement: ()=>parentRef.value,
estimateSize: ()=>72,
overscan: 5,
})
const vItems=computed(()=>virt.value.getVirtualItems())
watchEffect(()=>{
const last=vItems.value.at(-1)
if(!last) return
if(last.index>=allRows.value.length-1 && hasNextPage.value && !isFetchingNextPage.value)
fetchNextPage()
})
</script>
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...
