TanStackT
TanStack5mo ago
3 replies
worthy-azure

prefetchQuery vs ensureQueryData in SSR

Can someone explain the difference to me of these four?

loader: ({ context }) => {
        // 1. prefetch without await
        context.queryClient.prefetchQuery(...);
        // 2. prefetch with await
        await context.queryClient.prefetchQuery(...);
        // 3. ensure without await
        context.queryClient.ensureQueryData(...);
        // 4. ensure with await and await for the result
        await context.queryClient.ensureQueryData(...);
    },


I use useSuspenseQuery on the frontend


I know there's staletimes etc. But what I'm more interested in is/I want to acheive is this: I want to start the fetch on the server, not block the UI rendering, and have the useSuspenseQuery pick up on the frontend where the server-side fetch continue.
This means 'immediately show a loading UI and kick off the server-side data fetch at the same time, then simply use that data on the client side'.

To clarify, what I mean by the last one is I do NOT want another fetch request to trigger on the client.

I also read on one of TkTodo's replies here saying 'Also, when you use suspense, there is really no reason to await anything in the route loaders.' ensure vs prefetch query in deferred data loading

Given all that, I think '3' should be the way to go. But please correct me if I'm wrong.
Was this page helpful?