TanStackT
TanStack6mo ago
7 replies
sacred-rose

Understanding Route loader query vs component hook query

Can anyone help me to understand the difference between executing a query in the loader vs in the component?
I have these two examples

//$id.edit.tsx
// ensureQuery in the Route loader
export const Route = createFileRoute('/_app/orders/$id/edit')({
    loader: ({params, context: { queryClient } }) => {
        return queryClient.ensureQueryData(getOrderQuery(params.id));
    },
  component: EditOrder,
})
function EditOrder() {
    const order = useLoaderData({from: Route.id});
    console.log('EditOrder: data', order);
    return( ... )
}


and this

// No route loader. useQuery hook in the component
export const Route = createFileRoute('/_app/orders/$id/edit')({
  component: EditOrder,
})
function EditOrder() {
    const {id} = useParams({from: Route.id});
    const {data:order} = useQuery(getOrderQuery(id))
    console.log('EditOrder: data', order);
    return( ... )
}


From what I see, with the first one, the whole page waits to render while the data loads (maybe the router pending component shows) and there is no background fetching when you navigate back, or re-focus on the page (but there is caching).

With the second, the page starts to render immediately and you have to check for loading state in the jsx. Background fetches happen on navigation and re-focus.
Is it just a matter of what I want the loading and background fetching behavior to be?
Was this page helpful?