TanStackT
TanStack10mo ago
33 replies
skinny-azure

ensure vs prefetch query in deferred data loading

I'm trying to understand the difference between ensureQueryData and prefetchQueryData, esepcially in the context of deferred loading.

From the tanstack router docs:

export const Route = createFileRoute('/posts/$postId')({
  loader: async ({ context: { queryClient } }) => {
    // Kick off the fetching of some slower data, but do not await it
    queryClient.prefetchQuery(slowDataOptions())

    // Fetch and await some data that resolves quickly
    await queryClient.ensureQueryData(fastDataOptions())
  },
})


Then in the component:
function PostIdComponent() {
  const slowData = useSuspenseQuery(slowDataOptions())
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <SlowDataComponent />
    </Suspense>
  )
}


I get why we don't await the prefetch query, since we want to let it resolve in a <Suspense /> block.

But from the docs it seems like the main diff. between the two is that prefetch will never throw, and ensureQueryData will prefer to serve cached data.

But for instance, why can't both use prefetch or both use ensure?
Was this page helpful?