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.
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.
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.
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.
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.
3. React Sample and Data Fetching Strategies
It's a simple React sample with the main application file, scripts, models, and components. We'll be editing the code and adding components to the main application. The functions are already implemented and getting data from the CMS. The workshop focuses on data fetching strategies in JavaScript applications, covering the actual request and data retrieval. There's a Q&A section where a question about a URL error is addressed.
4. Data Fetching Strategies and Fetch API
We'll discuss the basic requests, state, and advanced features like paging. We have three options for data fetching: XMLHttpRequest, Axios, and Fetch API. Fetch API is recommended as it's easy to use and available in most browsers. A polyfill can be used for Internet Explorer. Fetch API is supported by current browsers, mobile browsers, and Node.js. For a task, we'll add a Fetch call to the Fetch TSX component and resolve the JSON response. Then, we'll import the component into the apt-tsx file. Some files may need to be renamed if they can't be compiled.
5. Troubleshooting and Deployment
Now it works. Axios was the problem. Cross-origin issue. Run it locally with Netlify dev and change the call to slash API slash get flights. Comment out React query and SWR. Create an environment file. Check if it works with CORS using Netlify CLI. Access control allow origin error. Working on getting Netlify functions compatible with CORS. Deploying to resolve the issue. Anyone depending on remote endpoint or running locally?
6. Deploying and CORS Issues
Deployed and encountered CORS issues. Tried different configurations but still not working. Finally found a solution by returning headers with status code and data. Now the function is working properly.
7. Using Axios for Data Fetching
Axios is a basic way to get data from a remote endpoint, providing more options for request and response interception. It offers features like response timeout, retry policy, and automatic JSON data transformation. In the component Axios.TSX, we use Axios.get to retrieve all flights from the specified URL. We also update the import and change the fetch to Axios in the App TSX file. However, we encounter a 404 error, which is due to a missing letter in the URL.
8. Intercepting Requests with Axios Interceptors
Let's move on to intercepting requests using Axios interceptors. By adding an interceptor, we can log all requests made by Axios to a specific URL. This is useful for debugging and working with cache. The code provided shows how to intercept requests and log them to the console. It also includes an optional error handler. After implementing the code, you can see the logged requests in the console when accessing the page. Remember to add a unique key prop to resolve any warnings. Now, let's proceed to the next task.
9. Retry Policy with AxiosRetry
I encountered a problem with the key, but it doesn't affect the data retrieval. Let's move on to the next task, which is the retry policy using AxiosRetry. This library allows us to define the number of retries and the delay between each retry. It's already installed in the project, so you can use it directly. Just provide the Axios instance and the config with the desired number of retries and retry delay. I'll fix the endpoint so you can try it out.
10. Troubleshooting and Axios Retry
We encountered an issue with the headers for the 500 status code. After making the necessary adjustments, the application is now up and running. We implemented Axios retry, which allows the application to keep trying to retrieve data even when errors occur. Additionally, we introduced the axios-timeout component, which sets a timeout for two seconds and displays a timeout error message. However, this component only works locally.
11. Data Fetching with SWR and React Query
We're going to explore the use of SWR and React query for data fetching and management. These libraries handle data fetching and provide features such as loading and error state handling, retry policy configuration, request deduplication, automatic revalidation, and paging and prefetching. SWR is a library developed by Vercel that focuses on data fetching and provides all the necessary features in a small bundle. We'll be using the useSWR hook instead of useEffect and provide a fetch function for the network request. Now let's move on to the next task and enhance the view for the remaining states.
12. Data Fetching with SWR
The SWR function is used to fetch data. It takes a key parameter that serves as an identifier for the data. The flights fetcher function is an async function that uses fetch to retrieve data from a remote endpoint. The useSWR hook is then called with the key and fetcher function. The isLoading, data, and error states can be accessed from the returned object. If isLoading is true, a loading message is displayed. The same can be done for the error state. Finally, the SWR function is used in the component, and the data is displayed in a table. If the data cannot be retrieved, a retry policy is automatically applied.
13. Using SWR for Data Fetching and Mutating
In this part, we explored the use of SWR for data fetching. We discussed the benefits of SWR over useEffect and how it automatically handles features like caching, loading states, and error handling. We also learned about the mutate function in SWR, which allows us to invalidate cached data and force revalidation. Additionally, we added state labels to indicate when data is being fetched or when an error occurs. Finally, we tested the network request behavior by duplicating the component and verifying that the request only happens once. Let's now move on to the next task.
14. Mutating Data with SWR
In this part, we explore how to mutate data using SWR. We learn that by calling mutate on a key, we invalidate the data in cache and trigger a refetch. This is useful when components rely on the data and need it to be updated. We also discuss the use of the SWR retry component, which allows us to implement a retry policy for fetching data. The component is already implemented, and we can simply change the endpoint to test different scenarios. Overall, mutate is a powerful tool for manipulating data in SWR and can be used for various purposes, such as updating, posting, or patching data.
15. Data Fetching with SWR and React Query
The retry policy allows for repeated attempts to fetch data, with the interval set to every five seconds. SWR provides many advantages over useEffect, including built-in cache, request deduplication, and support for different Next.js modes. React Query is a more advanced alternative to SWR, suitable for pagination and infinite scroll scenarios. It can be used with other frameworks like Vue.js and Angular. React Query has more features and a larger bundle size compared to SWR. It offers automatic retry of failed requests, query cancellation, and initial clear data for static site generators. However, configuring React Query can be more challenging, especially with TypeScript types. Overall, SWR is recommended for most cases, while React Query is suitable for advanced use cases.
16. Using React Query for Data Fetching
The React query component is already prepared and provides the same functionality as useSWR. It includes constants for is loading, is error, and is refetching data. Unlike useSWR, React query allows for distinguishing between the loading state and subsequent refetches. The query key remains the same, using the flights query function. Fetch API or XHR can be used to retrieve the data.
17. Implementing React Query for Dynamic Data Fetching
Let's explore the code for using the react query library. We need to remove the suffix and use the useQuery hook. The query key is an object that allows for multiple keys in any order. The flightsFetcher function is used as the query function. We can add labels for loading, error, and refetching. After fixing the fetch, we can see the application in action and observe the appropriate labels based on the background actions. The labels help inform the user about the data fetching status.
18. React Query Pagination and Final Remarks
The React query pagination allows for displaying or hiding next and previous buttons using the isPreviousData state boolean. The query key includes the page parameter, which can be incremented or decremented to retrieve different data. The React query is useful for advanced use cases with pre-built initial data, but it can be challenging to configure correctly. There are many features we couldn't cover in this workshop, but the choice between useSWR, React query, fetch API, and Axios depends on the project's needs. It's recommended to choose the one that best suits the specific use case. If you have any questions, feel free to ask in the chat. This concludes the workshop, and if you want to get in touch, you can find a link to the speaker's Twitter and Discord server in the presentation. Thank you for joining, and if you're in London next week, visit our booth.
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.
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
WorkshopFree
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
Comments