React Query vs. SWR: The Best Way to Fetch Data in 2021

Published at: May 15, 2021

When building React applications, handling API calls and managing the data flow can quickly become complex. Traditionally, developers relied on useEffect for API calls and managing state, but this approach has some limitations. React Query and SWR have emerged as two powerful libraries for data fetching and caching, offering much-needed solutions to common challenges.

In this post, we’ll compare React Query and SWR, two of the most popular libraries for fetching data in React, and discuss why they are preferred over traditional data-fetching methods like useEffect.

1. Why You Should Stop Using useEffect for API Calls

Before diving into the comparison, let’s quickly address why relying on useEffect for API calls is not the best practice anymore.

While useEffect is a great hook for managing side effects in React, it’s not designed specifically for data fetching. When you use useEffect to fetch data, you often end up with:

  • Manual management of loading, error, and success states: This can quickly clutter your code, especially when dealing with multiple API calls.
  • No automatic caching or refetching: Once data is fetched, you need to manually implement caching, refetching, and background updates.
  • Verbose code: Handling side effects like API calls with useEffect often leads to more boilerplate code and can be harder to maintain as the application grows.

That’s where libraries like React Query and SWR come into play. Both offer solutions to these challenges by abstracting away complex state management and providing useful features like caching, background fetching, pagination, and more.

2. What Is React Query?

React Query is a data-fetching and caching library for React that simplifies server state management. It helps you fetch, cache, and sync data in your React apps while providing a wide range of features for optimizing your data-fetching logic.

Key Features of React Query:

  • Automatic Caching: React Query automatically caches your API responses, reducing unnecessary network requests and speeding up your app.
  • Automatic Refetching: The library refetches data automatically when it becomes stale, ensuring that the data remains fresh.
  • Background Data Syncing: React Query can refetch data in the background when the app regains focus or reconnects to the network.
  • Pagination and Infinite Query Support: React Query simplifies the management of paginated and infinite scroll data, making it easier to work with large datasets.
  • Query Invalidation: You can invalidate queries when you make changes to the server data, ensuring that your UI stays in sync with the server.

React Query is ideal for apps that require complex server-side data management and real-time updates.

Example Usage:

import { useQuery } from 'react-query';

const fetchData = async () => {
  const res = await fetch('https://api.example.com/data');
  return res.json();
};

const MyComponent = () => {
  const { data, error, isLoading } = useQuery('data', fetchData);

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

  return <div>{JSON.stringify(data)}</div>;
};

3. What Is SWR?

SWR is another popular data-fetching library, developed by Vercel, the creators of Next.js. It stands for stale-while-revalidate and implements a caching strategy that allows you to quickly display stale data while fetching the latest version in the background.

Key Features of SWR:

  • Stale-While-Revalidate Caching: SWR fetches data in the background and displays the cached data immediately, improving the perceived performance.
  • Automatic Revalidation: SWR automatically revalidates the data when the component mounts or when the user re-focuses the window.
  • Optimistic UI: SWR allows you to implement optimistic updates, making your app feel snappier by assuming that changes will be successful.
  • Interval Refetching: You can specify an interval for data refetching, ensuring that the data is kept up-to-date at regular intervals.
  • Minimalistic API: SWR provides a simple API that requires very little configuration to get started.

SWR is a great choice for lightweight applications where caching and revalidation are key, and it’s especially popular with Next.js projects.

Example Usage:

import useSWR from 'swr';

const fetchData = async (url) => {
  const res = await fetch(url);
  return res.json();
};

const MyComponent = () => {
  const { data, error } = useSWR('https://api.example.com/data', fetchData);

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

  return <div>{JSON.stringify(data)}</div>;
};

4. React Query vs. SWR: A Comparison

While both React Query and SWR serve similar purposes, there are some key differences to consider when deciding which library to use for your project.

React Query:

  • Advanced Features: React Query offers more advanced features such as pagination, infinite scrolling, query invalidation, and caching management, making it ideal for complex data management scenarios.
  • Built-in Mutations: React Query provides built-in support for mutations (i.e., modifying server data), which is useful for apps with frequent updates or forms.
  • Global State Management: React Query also allows you to manage server state globally, which is great for apps with a shared state across multiple components.

SWR:

  • Simplicity and Minimalism: SWR is simpler and more minimalistic than React Query. It focuses on fetching data with a “stale-while-revalidate” caching strategy, making it a perfect fit for smaller, lightweight apps.
  • Next.js Integration: SWR is tightly integrated with Next.js, which makes it a natural choice for Next.js projects. Its API is simple, allowing you to get up and running with minimal configuration.
  • Less Overhead: SWR provides all the necessary caching and revalidation features, but it doesn’t have the complexity of React Query. For many use cases, SWR’s simplicity is an advantage.

5. When to Use React Query or SWR

  • Use React Query if:
    • You need advanced features like paginationinfinite scrollingquery invalidation, or mutation support.
    • Your app has a complex state management need with multiple sources of server data.
    • You are building a large-scale application where server state management plays a crucial role.
  • Use SWR if:
    • You prefer a simple and lightweight solution for data fetching with caching and revalidation.
    • You’re working on a Next.js project and want to take advantage of its seamless integration.
    • Your app requires stale-while-revalidate caching and doesn’t need advanced state management features.

6. Conclusion

Both React Query and SWR are excellent choices for fetching and caching data in React apps, and both move beyond the limitations of traditional useEffect-based data fetching. Choosing between the two comes down to your project’s needs:

  • For advanced features and complex data management, React Query is the clear winner.
  • For a simpler, minimalistic solution with automatic revalidation and cache-first strategies, SWR is a great choice.

In 2021, React Query and SWR have quickly become the go-to solutions for data fetching in React, and they make managing remote data in your app easier and more efficient than ever.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *