Optimizing Data Fetching with SWR & React Query

  • Managing data fetching and caching effectively using SWR and React Query.
  • Implementing request deduplication to optimize network resource usage.
  • Utilizing Axios for handling requests with retry policies and interceptors.
  • Adopting FETCH API and Axios for simplified and efficient data fetching.
  • Leveraging SWR's and React Query's advanced features for state management and error handling.

When developing dynamic web applications, efficient data fetching and state management are crucial. With the right tools and techniques, developers can optimize their applications to reduce network load, enhance user experience, and maintain data consistency. This article delves into various data fetching strategies in JavaScript, highlighting the use of SWR and React Query, along with essential practices in managing API requests.

One of the core techniques involves utilizing SWR for data fetching. SWR, which stands for 'stale-while-revalidate', is a library that provides a robust solution for handling data fetching. It works by fetching the data once from a remote endpoint and caching it. If multiple components need the same data, SWR ensures that the network request is made only once, thus implementing request deduplication. This is particularly useful in scenarios where different components in an application require access to the same data source.

Request deduplication is a vital feature for optimizing network usage. By ensuring that each piece of data is fetched only once, developers can minimize redundant requests. This not only conserves bandwidth but also improves the performance of the application by reducing the time spent waiting for network responses.

Another significant advantage of using SWR is its ability to handle automatic revalidation. When a component requests data, SWR checks if the data is already in the cache. If it is, the data is immediately provided to the component while a revalidation process occurs in the background. This ensures that the application uses the most up-to-date information without compromising on speed.

In addition to SWR, React Query is another powerful tool for managing data fetching in JavaScript applications. While it shares many features with SWR, React Query is particularly suited for more complex data management scenarios such as pagination and infinite scrolling. It offers a more granular control over query keys and provides detailed states for loading, refetching, and error handling.

React Query's ability to handle query cancellation is a notable feature. If a component is unmounted before its data fetching request completes, React Query can automatically cancel the request, freeing up resources and preventing unnecessary network activity. This is especially beneficial in applications with dynamic interfaces where components frequently change.

To maximize the capabilities of SWR and React Query, developers often integrate them with Axios or FETCH API for handling HTTP requests. Axios simplifies the process of making requests by providing features like request and response interception, timeout handling, and automatic JSON data transformation. These features make it easier to manage the complexities of interacting with remote APIs.

Axios also supports retry policies, allowing developers to specify how many times a request should be retried in case of failure. This is crucial for maintaining resilience in applications that rely on unreliable networks or endpoints. By defining a retry strategy, developers can ensure that their applications remain functional even when network conditions are suboptimal.

For developers working with FETCH API, it's important to note that it is widely supported by modern browsers, excluding older versions like Internet Explorer 11. The FETCH API offers a straightforward syntax and does not require additional packages, making it a preferred choice for many developers. However, in cases where browser compatibility is a concern, a polyfill can be used to extend support to older browsers.

Incorporating these data fetching strategies and tools into JavaScript applications leads to more efficient, reliable, and scalable solutions. By leveraging the unique strengths of SWR, React Query, Axios, and FETCH API, developers can create applications that handle data dynamically and responsively, enhancing the overall 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.

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.
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 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
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.
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 API Design – Lessons Learned
React Advanced 2024React Advanced 2024
26 min
React Query API Design – Lessons Learned
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.
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.