Course contentsShow
← React
Lesson 1811 of 2,39642. Data Fetching LibrariesFree lesson

Migration Considerations: SWR to TanStack Query

Key differences in API patterns, caching strategies, and features when moving between the two libraries.

Migration Considerations: SWR to TanStack Query

What you'll learn: The key API and architectural differences you'll encounter when migrating from SWR to TanStack Query.

Core Philosophy Shift

While SWR and TanStack Query both implement stale-while-revalidate patterns, their APIs and design philosophies differ significantly. SWR emphasizes simplicity with a single hook (useSWR) and implicit configuration, while TanStack Query offers explicit control through separate hooks (useQuery, useMutation) and fine-grained cache management.

Think of it like switching from automatic to manual transmission — you gain more control, but must be more deliberate about your choices.

Major API Differences

Hook Names: SWR's useSWR becomes useQuery. SWR's useSWRMutation becomes useMutation.

Query Keys: SWR uses strings as keys; TanStack Query uses array-based keys that support variables. Your useSWR('/api/user') becomes useQuery({ queryKey: ['/api/user'], queryFn: ... }).

Fetcher Function: SWR accepts a global fetcher via SWRConfig; TanStack Query requires explicit queryFn per query (or global default in QueryClient).

Configuration Mapping

  • revalidateOnFocus → refetchOnWindowFocus
  • revalidateOnReconnect → refetchOnReconnect
  • refreshInterval → refetchInterval
  • dedupingInterval → automatic (5 seconds default)
  • No direct equivalent to SWR's fallbackData — use initialData or placeholderData

Caching Strategy Changes

SWR caches by key string; TanStack Query uses structured cache with staleTime and cacheTime/gcTime. You'll need to explicitly set staleTime to replicate SWR's always-stale-by-default behavior, or embrace TanStack Query's more aggressive caching.

Mutations are more powerful in TanStack Query with built-in optimistic update patterns, but require more setup than SWR's simpler approach.

Key Takeaway: Migrating from SWR to TanStack Query means trading simplicity for power — expect more boilerplate but gain finer control over caching, refetching, and mutation coordination.