Back to blog

React Query vs SWR: Which Data Fetching Library is Better

Managing client-side API requests and server state in React applications has historically been complex. Standard combinations of useEffect and useState lead to bug-prone boilerplate, race conditions, lack of cache sharing, and redundant network requests.

To solve this, most React developers use a data-fetching library. The two dominant choices are SWR (developed by Vercel) and TanStack Query (formerly known as React Query).

In this guide, we will compare SWR and React Query, look at their caching strategies, analyze bundle sizes, and help you select the best fit for your React project.

SWR: Stale-While-Revalidate (Lightweight and Simple)

SWR’s name comes from the HTTP RFC 5861 caching strategy: Stale-While-Revalidate. The core philosophy of SWR is fetching data, displaying the cached data instantly (stale), and then validating the data in the background to serve updated content (revalidate).

SWR is designed to be lightweight, simple, and require minimal boilerplate.

Basic SWR Setup

import useSWR from 'swr';

const fetcher = (url: string) => fetch(url).then((res) => res.json());

export function UserProfile() {
  const { data, error, isLoading } = useSWR('/api/user', fetcher);

  if (error) return <div>Failed to load</div>;
  if (isLoading) return <div>Loading...</div>;
  return <h1>Hello {data.name}!</h1>;
}

React Query: Full-Featured Server State Manager

TanStack Query (React Query) is not just a fetching utility; it is a full-featured state management database for asynchronous data. It provides absolute control over how data is cached, garbage collected, updated, and mutated.

Basic React Query Setup

Unlike SWR, React Query requires wrapping your application in a client provider and utilizes structured array-based keys to manage queries.

import { useQuery } from '@tanstack/react-query';

async function fetchUser() {
  const res = await fetch('/api/user');
  return res.json();
}

export function UserProfile() {
  const { data, error, isLoading } = useQuery({
    queryKey: ['user'],
    queryFn: fetchUser,
  });

  if (error) return <div>Failed to load</div>;
  if (isLoading) return <div>Loading...</div>;
  return <h1>Hello {data.name}!</h1>;
}

Detailed Feature Comparison

1. Bundle Size and Footprint

  • SWR: Extremely lightweight, weighing only around 1.5 KB (gzipped). It has zero external dependencies, making it ideal for performance-focused sites.
  • React Query: Larger, weighing around 13 KB (gzipped). The extra weight is justified by its extensive feature set, but it might be overkill for simple websites.

2. Mutations and Optimistic Updates

  • SWR: Supports basic mutation via a mutate function. You can manually trigger a refetch or update the local cache immediately (optimistic updates).
  • React Query: Features a robust, dedicated useMutation hook. It handles optimistic updates via an advanced execution pipeline featuring onMutate, onError, and onSettled callbacks, making complex form submissions highly structured.

3. Caching Lifecycles

  • SWR: Simple caching model. It relies mostly on refetching on window focus, network reconnection, and interval ticking.
  • React Query: Advanced caching lifecycle. You can configure precise durations for:
    • staleTime: How long fetched data is considered fresh before needing a background update.
    • gcTime (formerly cacheTime): How long unused query data remains in memory before being garbage collected.

Summary: Which to Choose?

Metric SWR React Query
Bundle Size ~1.5 KB ~13 KB
Query Keys String / Function Array-Based Keys
Mutation API Basic mutate Dedicated useMutation
Infinite Queries Supported via useSWRInfinite Advanced useInfiniteQuery
DevTools Third-party / Community Native, dedicated DevTools

Choose SWR if:

  1. You are building lightweight web applications where bundle size is critical.
  2. You only need standard GET queries with auto-revalidation (focus/network re-connection) and do not write complex mutations.
  3. You are deploying to Vercel/Next.js and want a tool that integrates natively out of the box.

Choose React Query if:

  1. You are building a complex dashboard, SaaS platform, or full-stack application with hundreds of API endpoints.
  2. You need advanced data management features like infinite scrolling, query caching dependencies, and automatic retry behaviors.
  3. You rely heavily on mutating data, executing optimistic updates, and debugging queries via a dedicated DevTools interface.

Conclusion

Both SWR and React Query are great improvements over native useEffect fetching. SWR excels in simplicity and weight, serving as a perfect utility for simple CRUD apps. TanStack Query remains the industry standard for large enterprise applications, providing a robust database-like runtime to manage complex server states with ease.