Fetch, useEffect, React Query, SWR, what else?

Rate this content
Bookmark

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 Conference 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.

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.

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.

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

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.

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.

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

Short description:

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.

So, hello, everyone. I think it's a good time to start now. It's one minute after the time, a few more minutes to join, but we can already start with the basics and introductions. We're here in a Zoom call. If there is anything, you know, you need to ask or if you need more time for anything, then feel free to use the chat window. I actually managed to have it up and running on my next screen, so I'll see hopefully all your messages.

So, feel to say hi. Tell me where you're coming from. I hope it is much nicer weather than it is here in Brno, Czech Republic for me. It is a bit dark already, but it is actually a great time to do a workshop and spend time online, you know? Overall, I hope you can all see my screen. It is currently showing power point presentation. If you can just let me know if you see that because that is probably the biggest prerequisite to this workshop. Yes. Hello to India. That's nice. Coming from France, perfect. Same other way. Christof, I'm filling for you. It is October. What can we do? If you're coming to London next week, it will about to start. And there's a lot of people there. That is great. So, yeah, there we go. And we have a Prague here as well. Nice. It is great to meet you, all of you guys. I hope you're going to have fun. You're going to learn something new today. And the biggest achievement I will do today is just to have fun. To learn something new and see what we can do in the allocated time. Now, I aim to make the workshop under two hours so that we don't lose concentration. It's for most of us, it's after work time right now. So let's get to it. And let's see what we can do.

So, first of all, I'm Andrey. I'm a developer evangelist for Content.AI. We're a headless CMS spender. But today's workshop is not going to be about headless CMS at all. So this is just one slide to let you know where I'm coming from. Overall, we're going to be talking about data fetching strategies. And the agenda for today will be the following. So, first of all, I want to show you or I want to talk to you about the actual data fetching options that we have in JavaScript. That will be about FetchAPI. Then we're going to talk about advanced features in data fetching. that means how do we handle errors, how can we intercept requests. How can you implement or configure the retry policy? And then we're going to talk about processing the data on the application side. So, right now we call it data fetching. But libraries that actually let us do all that, they also have caching mechanism and other features in place that make it easier for us. So, we're going to look at some advanced use cases as well. We're going to look at the revalidation cases, that means when you have data in cache, you need to revalidate it either automatically or manually, or you want to prevent it actually, that's also one of the use cases. And the last one will be paging, which is almost on every project that needs to work with some lists of data. That's about it. I think that's a pretty packed agenda for today. Now, just to to give you guys an idea, this is going to be at the intro level. If you're an expert on React, maybe this will be a bit boring for you, but there will be a lot of examples, a lot of show cases, so you can test it on your own. If you have Visual Studio prepared, that's a good start. Just so you know, I won't go into the large or great details of React query or of USEr's VR and so on, because we could be here all day. Yeah, so, just to give you an idea of how this is going to work, now, of course, this is recorded, so if you need to get back to any point of the webinar or workshop, you can do that later, and I'll also share the presentation. Yeah, so, you'll get all the slides. You'll get all the codes. No worries at all. And if there is anything that I can do for you, if you need me to answer anything or if you need more time to do the exercises, then let me know in the chat window. I did the examples so that you can follow along. So, I'll give you the codes and I will give you time to work on the examples. It's very easy, nothing to be worried about. It's pretty much just so that you get your hands on the actual code, so that you don't just look at what I'm doing but you also try it out on your own. So that's about the agenda and first of all, what I wanted to show you is the application showcase, the application that we'll be working with because obviously for everything we do in the workshop we need to have some kind of a front-end. So, this is what I actually created. It's just a nice picture of a Swiss aircraft landing in Zurich but it's just to make the website look nice. This is a little bit off but that's because I think there is a HTML tag mix up somewhere but this is just a table of flights that could be on an airport.

2. Introduction to Data Fetching

Short description:

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.

It contains flight numbers origins destinations and so on. It doesn't really matter what the table shows. It's about the data and the network request that we'll be making.

Just so you know, all the data they are stored in a headless CMS. Content, as I said, I work for them but we're not going to work with the CMS at all. I prepared Netlify functions that will actually give us the data from API handlers so just so you know it's going to be giving us data about flights and this table is something we want to accomplish to have it listed here. There will be more things like next and previous page and so on. We'll get to that but just so you know this is the front end and we'll see how we can get it to work. So that's the most important thing now.

Another thing and that will be the first task for you guys. There is GitHub repository with the URL that is right now on the screen. I'm going to send you the link to it to the chat window so you don't have to write it down from the powerpoint presentation. So if you want to go there, there are two branches. One is workshop start, one is workshop results. So obviously you want to start with the workshop start. The readme is just a sample from creating the React app so not really relevant for this workshop. But what I want you to do is just clone the whole repository somewhere where you can run code. Somewhere we can open with Visual Studio Code. It contains all the files that we will need. So I'll give you a few minutes to actually do that. The start is not going to work. It's also not going to compile. So don't be surprised because it has some code missing. But we'll work on that. So I'll give you a few minutes to do that. The link is there so we should be good to go in a few moments. Let's go through the repo so you're up to speed with everything.

So there are two parts of what we'll be doing today. We'll focus a lot on the frontend part. So the backend part is there just to support us. And to understand how it works is there is a folder called functions which has four functions implemented. What they do, oh, by the way, while you're at it you might as well run npm i to install all the packages. I already have them here so I don't have to do it, but you might want to install the node modules while we talk about the repository. So, as I mentioned the data are coming from a Headless CMS. Now the Headless CMS has a project somewhere, it has environment id somewhere. It gives us data about the flights. Now, we don't have to run this. If you have Netlify CLI running locally, I can give you an environment id which you're going to have to pass into your environment file if you want to run the functions locally. That's also possible, but you don't have to do it. The functions are already deployed on Netlify. Let me give you the address of that. And that's actually here. So this is the URL of all the functions. They are already deployed there. So we should be able to get similar results as I'm getting. This is actually getting all the flies. This would be another function that will sometimes give me results, sometimes give me 500. So seems to be working well, so again you can run it locally if you want. I can give you the environment ID. If you don't want to run locally then this will be the address that you will use in the fetch calls. So that's the first part, those are the functions. They are configured to be accessible via slash API slash name of the function. You see there are a couple of them. They all do the same thing but the first one actually gives you all the flights. The slow one will actually give you all the flights after five seconds. So this is just a simulator we can retry or simulate timeouts. There is one that's called unreliable which will give you the results only once in five tries. So based on a random number. And there is one that apart from the will give you the total number of flights that are available. So we can do paging later. So these are all the functions. It's all pretty the same. And again, you don't have to run it locally. I'll give you the URL so you can run it. We can all work with it from the remote endpoint. And so this is the first part. These are the functions. Then, of course, there is index TSX. It's a simple React sample, so it has only the app inside.

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 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.
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.
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 Conference 2023React Advanced Conference 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 Conference 2021React Advanced Conference 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.
Thinking in React Query
React Summit 2023React Summit 2023
22 min
Thinking in React Query
Top Content
Watch video: Thinking in React Query
React Query is not a data fetching library, but an Asian state manager. It helps keep data up to date and manage agent life cycles efficiently. React Query provides fine-grained subscriptions and allows for adjusting stale time to control data fetching behavior. Defining stale time and managing dependencies are important aspects of working with React Query. Using the URL as a state manager and Zustand for managing filters in React Query can be powerful.