Course contentsShow
← React
Lesson 1884 of 2,39643. RoutingFree lesson

Integration with TanStack Query

Combine TanStack Router loaders with TanStack Query for optimal data fetching with deduplication.

Integration with TanStack Query

You'll learn how to combine TanStack Router's loaders with TanStack Query to get both type-safe routing and intelligent query management.

Why Combine These Libraries?

TanStack Router gives you type-safe routing and loaders, while TanStack Query provides powerful caching, deduplication, and background refetching. When you use them together, you get the best of both worlds: queries initiated by route loaders benefit from Query's cache, preventing duplicate network requests when multiple components need the same data.

The Pattern

Instead of fetching directly in a route loader, you reference the same query configuration that your components use. The loader calls TanStack Query's ensureQueryData or queryClient.prefetchQuery, while components use useQuery with identical query keys.

import { createRoute } from '@tanstack/react-router'
import { QueryClient } from '@tanstack/react-query'

const queryClient = new QueryClient()

// Define your query configuration once
const userQuery = (userId: string) => ({
  queryKey: ['user', userId],
  queryFn: () => fetchUser(userId)
})

// Use it in the loader
const userRoute = createRoute({
  path: '/user/$userId',
  loader: async ({ params }) => {
    await queryClient.ensureQueryData(userQuery(params.userId))
  }
})

In your component, call useQuery with the same configuration:

function UserProfile() {
  const { userId } = useParams({ from: '/user/$userId' })
  const { data } = useQuery(userQuery(userId))
  // Data is already cached from the loader!
}

The Magic: Deduplication

Because both the loader and component reference the same query key, TanStack Query sees they're requesting identical data and serves from cache. No duplicate fetches, full type safety, and automatic refetching when needed.

Key Takeaway: Integrate TanStack Router loaders with TanStack Query by sharing query configurations—loaders prefetch, components consume, and Query handles intelligent caching between them.