SWR cho app đơn giản read-heavy với Next.js (~4KB, minimal API); React Query cho app phức tạp cần mutations, optimistic updates, DevTools, granular cache control (~13KB nhưng feature-rich hơn 3x).
- So sánh chi tiết React Query (TanStack Query v5) vs SWR v2: Bundle size — SWR ~4KB, React Query ~13KB (nhưng features nhiều hơn 3x).
- API philosophy — SWR ưu tiên simplicity và convention, React Query ưu tiên control và flexibility.
- Mutations: React Query có
useMutationhook đầy đủ (onMutate, onSuccess, onError, onSettled, optimistic updates), SWR không có mutation hook — thường dùng thư viện khác hoặc tự viết. - DevTools: React Query có DevTools panel chi tiết, SWR không có DevTools chính thức.
- Infinite queries: cả hai có, nhưng React Query có
getNextPageParam+getPreviousPageParamlinh hoạt hơn. - Prefetching + SSR: React Query có dehydrate/HydrationBoundary pattern rõ ràng hơn, SWR có
fallbackprop đơn giản hơn. - Cache key: React Query dùng array (type-safe, fuzzy match), SWR dùng string/function.
- Offline support: React Query có
networkModeoption, SWR basic. - Kết luận: chọn SWR khi app chủ yếu read-only data fetching, team muốn đơn giản, bundle size quan trọng, dùng nhiều với Next.js pages router.
- Chọn React Query khi cần mutations phức tạp, optimistic updates, DevTools cho debugging, team cần full-featured solution.
SWR for simple read-heavy apps with Next.js (~4KB, minimal API); React Query for complex apps needing mutations, optimistic updates, DevTools, granular cache control (~13KB but 3x more features).
- React Query (TanStack Query) and SWR are both data-fetching libraries for React, but with different philosophies: React Query: more feature-rich — mutations with lifecycle callbacks (onMutate, onSuccess, onError), optimistic updates, query invalidation, infinite queries, useQueries; granular cache control (staleTime, gcTime, query filters); Suspense support; DevTools; better for complex applications with many mutations and cache dependencies.
- SWR: simpler API, smaller bundle size; created by Vercel, integrates naturally with Next.js; good for read-heavy applications with simpler caching needs; supports Suspense; mutate() is simpler but less powerful than React Query mutations.
- When to choose: React Query for complex apps with many mutations, optimistic updates, and sophisticated cache management; SWR for simpler apps, smaller bundle requirements, or when deep Next.js integration is a priority.