SWR vs React-Query
Tags: react, javascript, webdev, programming
Published: 2022-12-22 14:36:10

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

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

// Or with npm:
npm install swr
```
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:

```js
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>;
}
```

To use **React-Query**, you will need to [install the library](https://tanstack.com/query/v4/docs/react/installation) 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:

```js
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>;
}
```

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.