DEV Community

Cover image for SWR vs React-Query
Letícia Vieira
Letícia Vieira

Posted on • Edited on

SWR vs React-Query

Data fetching is an essential part of any modern web application. It allows us to retrieve data from APIs and other sources to display it to the user. In a React application, many different libraries and techniques can be used to manage data fetching.

What is?

SWR (stale-while-revalidate) and React-Query are the two most popular libraries that can be used to manage data fetching in a React application. Both libraries can help you make HTTP requests, cache the results of those requests, and automatically update your UI when the data changes.

The main difference between both

One of the main differences between the two libraries is the level of features and functionality they provide. SWR is a smaller library that focuses on providing a simple way to fetch and cache data, while React-Query is a larger library that provides many more features, including pagination, polling, refetching, and error handling.

Another difference is the way the libraries handle caching and data refreshing. In SWR, you can use the staleTime option to specify how long the data should be considered fresh before it is considered stale and eligible for revalidation. In React-Query, you can use the cacheTime option to specify the length of time that data should be kept in the cache before it is considered stale and eligible for refetching.

Overall, the main difference between SWR and React-Query is the level of features and functionality they provide. SWR is a good choice for simple data fetching needs, while React-Query is a good choice for more advanced or complex data fetching requirements.

How to use it?

To use SWR in a React application, you will need to install the library

// Inside your React project directory, run the following:
yarn add swr

// Or with npm:
npm install swr
Enter fullscreen mode Exit fullscreen mode

then wrap your HTTP request in a useSWR hook. The hook will return the data from the request. Here is a code snippet of how you might use the useSWR hook to fetch data from an API:

import useSWR from 'swr';

function fetcher(url) {
  return fetch(url).then(res => res.json());
}

function Users() {
  const { data, error } = useSWR('/api/users', fetcher);

  if (error) return <div>Failed to load data</div>;
  if (!data) return <div>Loading...</div>;

  return <div>{data.name}</div>;
}
Enter fullscreen mode Exit fullscreen mode

To use React-Query, you will need to install the library and then wrap your component with QueryClient. Once the library is installed, you can use the useQuery hook in your React component to fetch and manage data from an API. The useQuery hook accepts a queryKey and a queryFn as arguments, and returns an object with the data, loading state, and error state of the query.
Import useQuery and start using it in any functional component:

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

function Users() {
  const { data, error, isLoading } = useQuery(
    '/api/users',
    async () => {
      const res = await fetch('/api/users');
      return res.json();
    }
  );

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return <div>{data.name}</div>;
}
Enter fullscreen mode Exit fullscreen mode

Both SWR and React-Query provide many more options and configuration settings that you can use to customize the behavior of your data fetching. You can refer to the documentation for each library for more information.

Which one to choose?

The choice between using SWR or React-Query for data fetching in React app will depend on your specific needs and the complexity of your data dependencies.

SWR is a small library that was created by Vercel (formerly known as Zeit). It works by wrapping your HTTP request in a useSWR hook, which returns the data from the request and some helper functions. When the data is stale, the hook will automatically re-fetch the data in the background while continuing to return the stale data to the UI. This allows the UI to stay responsive while the data is being updated.

React-Query is a larger library that provides many more features than SWR. In addition to caching and automatic data refreshing, it also has features for pagination, polling, refetching, and handling errors. It also provides tools for optimizing the performance of your data fetching, such as the ability to batch and deduplicate requests.

In general, SWR is a good choice if you just need a simple way to fetch and cache data in your application. React-Query is a good choice if you need more advanced features or if you are working on a larger application with a lot of data dependencies.

Both libraries can be useful for improving the performance of your application by making it easier to fetch, cache, and update data in a performant way.

Top comments (6)

Collapse
 
igorsantos07 profile image
Igor Santos

Well written article and one of the first results on Google search about the two libs; however, it doesn't help much besides giving a feeling they are the same thing and a boilerplate example with the same basic use-case for both libs.

How is SWR different from RQ in terms of staleness behavior? From what you said, they both do the same thing. Also, no clue how RQ handles errors better than SWR, since both have the same error object you can use inside the component.

So.........?

Collapse
 
greggcbs profile image
GreggHume

yeah this article didnt help me decide at all and I have used RQ extensively . I guess i was hoping to learn a bit more about SWR but this article doesnt really tell much.

Collapse
 
juuni26 profile image
juuni26

not really much in-depth explanation and also you use staleTime in react-query for defining how much time the data is stale or needs to be updated. while cacheTime is just for setting how much time the data is cached if they are unused queries ( so it's kinda useless if they are active queries).

so this one from the post is not quite true

In React-Query, you can use the cacheTime option to specify the length of time that data should be kept in the cache before it is considered stale and eligible for refetching.

Collapse
 
bryan_guenther_1f273831d3 profile image
Bryan Guenther

This article simply isn't true. Some basic research will tell you SWR does support all the things you listed RQ does. There's another similar article making baseless claims on this website (dev.to). Are these paid articles or something?

Collapse
 
pcelac profile image
Info Comment hidden by post author - thread only accessible via permalink
Aleks

Incorrect statement for React Query cacheTime functionality!

Collapse
 
lvieira268 profile image
Letícia Vieira

Sorry, I don't think I quite understood what you meant. Can you explain better?

Some comments have been hidden by the post's author - find out more