SWR vs React Query: Efficient Data Fetching

Introduction to Data Fetching Strategies

Data fetching is a critical operation in modern web applications, especially those built with frameworks like React and Angular. The task involves retrieving data from remote endpoints to display it or process it further in the application. As front-end applications grow in complexity, efficient data fetching strategies become vital to ensure performance and a seamless user experience.

Traditionally, developers relied on XMLHttpRequest for making HTTP requests. However, with the advent of Fetch API and libraries like Axios, data fetching has become more streamlined and developer-friendly. These tools abstract away much of the boilerplate code involved in handling HTTP requests, making it easier to focus on the application logic.

Understanding SWR and Its Features

SWR, short for stale-while-revalidate, is a data fetching library developed by Vercel. It's designed to optimize data fetching and caching, enhancing performance and developer experience. SWR follows a simple principle: it fetches data from the cache first and then revalidates it in the background, ensuring that the application always displays the most recent data without unnecessary network requests.

One of the standout features of SWR is request deduplication. When multiple components need the same data, SWR ensures that the data is fetched only once, saving bandwidth and reducing load time. This is particularly useful in applications with complex component hierarchies where data dependencies overlap.

Another key feature is the mutate function, which allows developers to invalidate cached data and trigger a refetch. This is critical when the application state changes and the data needs to be updated promptly. Although the primary use case of mutate is to refresh cached data, it can also be used for more advanced operations like posting or patching data.

Exploring Fetch API and Axios

The Fetch API is a modern, native JavaScript API that provides a flexible and straightforward way to make network requests. It is widely supported across modern browsers, except for Internet Explorer, where a polyfill can be used to enable its functionality. The simplicity of Fetch API makes it a default choice for many developers, especially when working with newer projects.

Axios, on the other hand, is a popular library that offers additional features over the Fetch API, such as automatic JSON data transformation, request and response interception, and support for older browsers. Axios is based on XMLHttpRequest, making it compatible with a wider range of environments. It also simplifies handling of timeouts and retry policies, providing a robust solution for complex data fetching scenarios.

Implementing Retry and Timeout Policies

Handling network errors and timeouts is crucial for maintaining a smooth user experience. Both SWR and Axios offer ways to implement retry and timeout policies. With SWR, retry policies can be configured to automatically refetch data after a failed attempt, while Axios provides built-in support for retrying requests with exponential backoff, reducing the load on the server and network.

Timeout management is another important aspect. Axios allows developers to specify a timeout for requests, ensuring that the application doesn't hang indefinitely waiting for a response. This feature is critical when dealing with unreliable networks or endpoints that might be slow to respond.

Advanced Data Management with React Query

React Query is another library that enhances data fetching and state management in React applications. It provides a comprehensive set of tools for managing server state, including caching, pagination, and query cancellation. React Query is particularly useful for complex use cases like infinite scrolling and prefetching data.

The library offers more granular control over query keys, allowing developers to manage state more effectively. It also supports initial data loading, which is beneficial for static site generation. React Query's robust feature set makes it a powerful tool for applications that require advanced data management capabilities.

Conclusion

Choosing the right data fetching strategy and tools is crucial for building efficient web applications. SWR and React Query offer powerful features for managing server state and optimizing network requests. While SWR provides a lightweight solution with built-in caching and revalidation, React Query excels in handling complex data fetching scenarios.

For most projects, the choice between using Fetch API or Axios comes down to specific project requirements and browser compatibility needs. Understanding the strengths and limitations of each tool can help developers make informed decisions and build applications that deliver a smooth and responsive user experience.

Watch full talk with demos and examples:

Rate this content
Bookmark

From Author:

In this workshop, first, we’ll go over the different ways you can consume APIs in React. Then, we’ll test each one by fetching content from a headless CMS (with both REST and GraphQL) and checking in detail how they work.


While there is no advanced React knowledge required, this is going to be a hands-on session, so you’ll need to clone a preconfigured GitHub repository and utilize your preferred React programming editor, like VS Code.


You will learn:

- What diverse data fetching options there are in React

- What are advantages and disadvantages of each

- What are the typical use cases and when each strategy is more beneficial than others

This workshop has been presented at React Advanced 2023, check out the latest edition of this React Conference.

FAQ

Feel free to use the chat window to ask questions or request more time.

Please notify the presenter in the chat window if you cannot see the screen, as it is a key prerequisite for the workshop.

The workshop is aimed to be under two hours to maintain concentration.

Clone the repository, install the necessary packages using npm i, and ensure you have Visual Studio Code ready. Refer to the readme file for additional instructions.

SWR (stale-while-revalidate) is a data fetching library by Vercel that provides features like built-in cache, request deduplication, automatic interval-based revalidation, and easy configuration of retry policy. It is useful for handling data fetching more efficiently than useEffect.

The 'mutate' function in SWR is used to invalidate the cached data and force it to revalidate, ensuring that the application has the most up-to-date data.

React Query offers more advanced features such as automatic retry of failed requests, query cancellation, and initial stale data handling. It is suitable for complex use cases like pagination and infinite scroll, although it may require more configuration compared to SWR.

The workshop will cover data fetching strategies in JavaScript, including FetchAPI, handling errors, intercepting requests, configuring retry policy, processing data on the application side, caching mechanisms, revalidation cases, and paging.

Fetch API is a native JavaScript API that requires no additional packages and is supported by most modern browsers. It is a simpler and more straightforward option for basic data fetching needs.

Yes, the workshop is recorded, and you will be able to access it later. The presenter will also share the presentation slides and code.

Ondrej Polesny
Ondrej Polesny
102 min
12 Oct, 2023

Comments

Sign in or register to post your comment.
Video Summary and Transcription
This workshop covers data fetching strategies in JavaScript, focusing on Fetch API, Axios, SWR, and React Query. It provides examples and guidance on implementing these strategies in a React application. Troubleshooting and deployment issues, such as CORS, are also addressed. The workshop concludes by highlighting the advantages and use cases of SWR and React Query, and encourages participants to choose the best strategy based on their project's needs.

1. Introduction to Data Fetching Strategies

Hello everyone! Let's get started with the basics and introductions. Feel free to ask questions in the chat window. Today's workshop is about data fetching strategies in JavaScript. We'll cover FetchAPI, advanced features, processing data, revalidation, and paging. It's an intro-level workshop with lots of examples. You'll receive all the slides and codes. If you need assistance or more time for exercises, let me know. Now, let's take a look at the application showcase, a table of flights on an airport.
Read also

2. Introduction to Data Fetching

It's about the data and the network request that we'll be making. We'll focus on the frontend part. The backend part is there just to support us. The data are coming from a Headless CMS. The functions are already deployed on Netlify. You can run it locally if you want. The first part is about the functions and index TSX.

Watch more workshops on topic

Rethinking Server State with React Query
React Summit 2020React Summit 2020
96 min
Rethinking Server State with React Query
Top Content
Featured Workshop
Tanner Linsley
Tanner Linsley
The distinction between server state and client state in our applications might be a new concept for some, but it is very important to understand when delivering a top-notch user experience. Server state comes with unique problems that often sneak into our applications surprise like:
- Sharing Data across apps- Caching & Persistence- Deduping Requests- Background Updates- Managing “Stale” Data- Pagination & Incremental fetching- Memory & Garbage Collection- Optimistic Updates
Traditional “Global State” managers pretend these challenges don’t exist and this ultimately results in developers building their own on-the-fly attempts to mitigate them.
In this workshop, we will build an application that exposes these issues, allows us to understand them better, and finally turn them from challenges into features using a library designed for managing server-state called React Query.
By the end of the workshop, you will have a better understanding of server state, client state, syncing asynchronous data (mouthful, I know), and React Query.
Crash course into Astro and Storyblok
React Day Berlin 2023React Day Berlin 2023
119 min
Crash course into Astro and Storyblok
WorkshopFree
Arisa Fukuzaki
Arisa Fukuzaki
Headless architecture has gained immense popularity in recent years for its ability to decouple the frontend and backend, empowering developers to create engaging, interactive, and scalable web applications. 
In this workshop, we will quickly take a dive into the Headless World and Architecture. 
Additionally, we will build a blog website super quickly using Storyblok, a headless CMS that offers a real-time preview feature with nestable component approach, and Astro (3.0) which is already creating a buzz with the new app directory. 
- Master headless CMS fundamentals- Master an Astro & headless CMS approach- Use Atomic design in your Astro & Storyblok application- Creating pages, adding content and understanding how the dynamic routing works with headless
Building Blazing-Fast Websites with Next.js and Sanity.io
React Summit 2023React Summit 2023
71 min
Building Blazing-Fast Websites with Next.js and Sanity.io
WorkshopFree
Nancy Du
Nataliya Ioffe
2 authors
Join us for a hands-on workshop where we'll show you how to level up your React skills to build a high-performance headless website using Next.js, Sanity, and the JAMstack architecture. No prior knowledge of Next.js or Sanity is required, making this workshop ideal for anyone familiar with React who wants to learn more about building dynamic, responsive websites.
In this workshop, we'll explore how Next.js, a React-based framework, can be used to build a static website with server-side rendering and dynamic routing. You'll learn how to use Sanity as a headless CMS to manage your website’s content, create custom page templates with Next.js, use APIs to integrate with the CMS, and deploy your website to production with Vercel.
By the end of this workshop, you will have a solid understanding of how Next.js and Sanity.io can be used together to create a high-performance, scalable, and flexible website.
Crash Course Into Astro, Kontent.ai and Portable Text
React Summit 2023React Summit 2023
91 min
Crash Course Into Astro, Kontent.ai and Portable Text
WorkshopFree
Ondrej Polesny
Ondrej Polesny
During this crash course, we’ll create a new project in the headless CMS, create the content model and data using the Kontent.ai CLI. Then, we’ll use the content to build an Astro website including front-end components and rich text resolution using Portable Text.
This will be hands-on workshop, you’ll need VS Code, Git, NPM and basic knowledge of JavaScript. Don’t worry, I will explain all the steps as we advance through the workshop and you will be able to directly ask any questions.
Crash Course into Remix & Storyblok
Remix Conf Europe 2022Remix Conf Europe 2022
162 min
Crash Course into Remix & Storyblok
WorkshopFree
Facundo Giuliani
Arisa Fukuzaki
2 authors
You may read already about Remix. You probably already used it, and recently you may hear a lot about the headless CMSs. In this quick course, we will put all the pieces together, and I will show you why Storyblok in combination with Remix is the best combo for your next project. Stop by and try it yourself!
Table of content: - Introduction to Remix, atomic design & the headless world- Environment setup- Creating pages and understanding how the dynamic routing splat routes works- Future tips and Q&A
Prerequisite(s): Node.js installed, GitHub account.
Localizing Your Remix Website
React Summit 2023React Summit 2023
154 min
Localizing Your Remix Website
WorkshopFree
Harshil Agrawal
Harshil Agrawal
Localized content helps you connect with your audience in their preferred language. It not only helps you grow your business but helps your audience understand your offerings better. In this workshop, you will get an introduction to localization and will learn how to implement localization to your Contentful-powered Remix website.
Table of contents:- Introduction to Localization- Introduction to Contentful- Localization in Contentful- Introduction to Remix- Setting up a new Remix project- Rendering content on the website- Implementing Localization in Remix Website- Recap- Next Steps

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

React Query: It’s Time to Break up with your "Global State”!
React Summit Remote Edition 2020React Summit Remote Edition 2020
30 min
React Query: It’s Time to Break up with your "Global State”!
Top Content
Global state management and the challenges of placing server state in global state are discussed. React Query is introduced as a solution for handling asynchronous server state. The Talk demonstrates the process of extracting logic into custom hooks and fixing issues with state and fetching logic. Optimistic updates with mutation are showcased, along with the benefits of using React Query for data fetching and mutations. The future of global state management is discussed, along with user feedback on React Query. The Talk concludes with an invitation to explore React Query for server state management.
React Query API Design – Lessons Learned
React Advanced 2024React Advanced 2024
26 min
React Query API Design – Lessons Learned
Top Content
I'm super excited to be here today, giving my first live talk at an in-person conference. Dominik, the maintainer of React Query, walks through the API design decisions, including success stories, trade-offs, and mistakes. Tener Linsley designed React Query's medium-sized query API to be minimal, intuitive, powerful, and flexible. Major versions in open source require marketing efforts, but not primarily for adding new features. TypeScript is crucial for building projects and managing user demands in open source can be challenging. The addition of the max pages option improved performance and avoided unnecessary refetches. Inversion of control gives users flexibility, but mistakes can happen in API design. Open source requires time management and feedback from users. API design is influenced by typing ease and good TypeScript support. Getting involved in open source involves trial and error and joining community platforms like TanStack Discord. Dominik's journey started during the pandemic and he can be found on Twitter, TanStack Discord, and his blog.
Managing React State: 10 Years of Lessons Learned
React Day Berlin 2023React Day Berlin 2023
16 min
Managing React State: 10 Years of Lessons Learned
Top Content
Watch video: Managing React State: 10 Years of Lessons Learned
This Talk focuses on effective React state management and lessons learned over the past 10 years. Key points include separating related state, utilizing UseReducer for protecting state and updating multiple pieces of state simultaneously, avoiding unnecessary state syncing with useEffect, using abstractions like React Query or SWR for fetching data, simplifying state management with custom hooks, and leveraging refs and third-party libraries for managing state. Additional resources and services are also provided for further learning and support.
SolidJS: Why All the Suspense?
JSNation 2023JSNation 2023
28 min
SolidJS: Why All the Suspense?
Top Content
Suspense is a mechanism for orchestrating asynchronous state changes in JavaScript frameworks. It ensures async consistency in UIs and helps avoid trust erosion and inconsistencies. Suspense boundaries are used to hoist data fetching and create consistency zones based on the user interface. They can handle loading states of multiple resources and control state loading in applications. Suspense can be used for transitions, providing a smoother user experience and allowing prioritization of important content.
A Practical Guide for Migrating to Server Components
React Advanced 2023React Advanced 2023
28 min
A Practical Guide for Migrating to Server Components
Top Content
Watch video: A Practical Guide for Migrating to Server Components
React query version five is live and we'll be discussing the migration process to server components using Next.js and React Query. The process involves planning, preparing, and setting up server components, migrating pages, adding layouts, and moving components to the server. We'll also explore the benefits of server components such as reducing JavaScript shipping, enabling powerful caching, and leveraging the features of the app router. Additionally, we'll cover topics like handling authentication, rendering in server components, and the impact on server load and costs.
React Query and Auth: Who is Responsible for What?
React Advanced 2021React Advanced 2021
19 min
React Query and Auth: Who is Responsible for What?
Top Content
This talk introduces React Query and Auth, discussing how React Query maintains server state on the client and handles mutations and data updates. The day spa app example demonstrates the use of React Query to fetch data and handle user authentication. React Query is also useful for managing user data and ensuring accurate data from the server. The talk highlights the importance of addressing the three main players in user data: React Query, Auth Functions, and persistence across sessions.