Simplifying Data Management in React With React Query

Rate this content
Bookmark

This talk is about how React Query can simplify data management in React applications. The talk covers the basics of React Query, including its features for fetching and updating data, handling optimistic updates, composing queries and mutations, and managing errors and retries. By the end of the talk, attendees will have a clear understanding of how React Query can improve the user experience and reduce boilerplate in their React applications.

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

Watch video on a separate page

FAQ

React Query is a library that helps manage data fetching in React applications by providing features like caching, automatic refetching, and state management of fetched data. It simplifies building complex server-state applications by reducing the need for boilerplate code and improving performance through efficient data retrieval and memory management.

The four core concepts in React Query are: Queries (for fetching data), Mutations (for modifying data), Query Caching (to enhance performance by reusing previously fetched data), and Query Invalidation (to refresh query results under certain conditions). These concepts help in efficient data synchronization and state management.

React Query uses the 'useMutation' hook to handle data modifications such as POST, PUT, or DELETE operations. This hook facilitates updating or deleting data directly from the server and automatically integrates the changes into the React components, simplifying the process of state synchronization after data alterations.

Yes, React Query is well-suited for managing server-state data in scenarios that involve pagination, lazy loading, and infinite scrolling. Its efficient handling of data fetching and caching makes it ideal for loading and displaying large datasets smoothly, enhancing user experience in applications with extensive data lists.

React Query eliminates the need for manual setup of global state management for server-side data. It automates fetching, caching, and updating data, thereby reducing the amount of code needed and minimizing potential errors in data handling. Additionally, it optimizes memory usage and simplifies the implementation of complex features like data pagination and background updates.

React Query automatically removes unused data from the cache and manages memory efficiently. This ensures that the application uses resources optimally, maintaining high performance even in data-intensive environments. The library's built-in mechanisms prevent memory leaks and excessive data retention.

Typical use cases for React Query include fetching and displaying data from APIs, updating data on the server, implementing infinite scrolling and pagination, and managing server state in real-time applications. It is particularly useful in applications that require frequent data updates and where performance and user experience are critical.

Harsh Shah
Harsh Shah
16 min
23 Oct, 2023

Comments

Sign in or register to post your comment.

Video Summary and Transcription

Today's talk introduces React Query, a library that simplifies data management in React applications. It covers the core concepts and features of React Query, including data fetching, caching, and mutation. The talk also discusses query invalidation and cache time, highlighting how React Query optimizes performance and reduces code complexity.

1. Introduction to React Query and State Management

Short description:

Today's topic is simplifying data management using a project query. React Query is a helpful library that simplifies data fetching and state management. It provides various hooks and handles the loading, error, prefetching, and de-duplication of requests. Let's dive into React Query and explore its features.

Hey, so hello everyone. So today I'm going to talk about simplifying data management in using a project query. So this is a small thing about me. My name is Harsh. I'm a CTO at a company called Parallels Up. I'm also a Polygon advocate. I've done also 2x G-SoC. Also part of MIT Media Lab initiative. These are the following things which I'm doing in the community and work with a lot of startups and global companies.

So, yeah, let's move quickly to what is the React State Management. There are two types of state managements. One is global state management, another is data fetching. Global state management is basically how you are managing a state globally. Like you can pass a global variable and you can define the state and you can use it in the React State itself. And one is data fetching. Data fetching is you can fetch the data using APIs or other JSON formats on the head, and based on data fetching you do a query and pass the data and map the data.

So it's a very simple statement to have the state management in React. Then we can move to React Query, which we want to learn here. React Query is a helpful library which helps to manage our data fetching using catching and optimize our query requests and everything. React Query is very easily developed to fetch, update data using various sources and the library automatically handles your state of data fetching and catching. There are various hooks available in React Query itself. So we're going to see one by one what kind of hooks and what are the things available in React Query. So before we jump into React Query, let's understand how normal query or any kind of query works. The first state of React Query is basically a loading or error state. When you fetch any kind of data, first is like if data is huge, you put a loading or data is not fetched, you put an error state or something like something like try-catch or promises something. And then the second step is like prefetching. Prefetching is prefetch your data before rendering real data onto the side of a mobile or anything. So it's like prefetching, preflight request. De-duplication of a request is basically when you put a simple API call and is calling a multiple time API. It's like preflight API call first to check just data is coming or not.

2. React Query Concepts and Features

Short description:

Page initial and infinite scroll, mutation, retry and error, and the four core concepts of ReactQuery are covered. The main features include fetching and caching data, updating data in the background, optimized memory usage, and support for pagination, lazy loading, and infinite scrolling. React Query provides hooks like UseQuery and QueryClientProvider for fetching data. The UniqKey parameter and array notation are used in the latest version of query.

And second call is like confirmation of data. Page initial and infinite scroll is one of the biggest example of people are using Great Query and state management. Page initial and infinite scroll is one of the tough thing to do sometimes because when the data is huge, you need to complicate and slice and do everything and manage your state and query everything data. Mutation is ultimately duplications. And retry and error is like, try if data is getting fetched is not getting error, try again. That's why I'll try and fetch.

So let's move to the core concepts. What are the core concepts in the react queries? So there's a four core concept in the react query. One is query, which you request the data from a remote source Such like API points or database and using a react query hook, you can fetch all the queries. Second one is mutations, where you add the request in the API call and you can modify the existing data using the simple hooks called useMutation hooks. Third one is query catching. When you're doing a query, you want to do some type of catching like getting the data from the API itself. So ReactQuery provides automatically ReactQuery catching function and they store your result as a catch and you can use catch in multiple ways. And querying validation is the process of making query for invalid state on everything. And these are the four core concepts of ReactQuery.

Okay, so let's move to the main feature of ReactQuery. Main feature is for ReactQuery why we use, want to use ReactQuery or why you guys want to use ReactQuery other than the other Google statement. One is fetching, fetch and catch data Other thing is you can use that fetch data anywhere in the app itself. There is no need of defining global state and putting data here and there. You can update your data in background like you can use mutations and based on mutations you can update your data and modify your data. Memory management is amazing in ReactQuery. You can remove or you can, whichever data you are not using It's optimized your memory uses. For pagination, lazy loading and infinite scrolling This is the best library you can use to do just pagination, lazy loading and infinite scrolling. Not only this function but you can configure CreateQuery in whatever manner you want Like window focus or refetching or query delaying It depends on the query you want to do but this helps you a lot in query management and state management. Let's learn one by one or let's understand one by one What are the core hooks in a React Query When we are fetching the data one of the common hooks we use when we are doing a React Query is UseQuery you can see here React Query when you use, you need to run one hook, it's called QueryClientProvider It's ultimately a wrapper which is a tool which helps you to query using UseQuery and the child component itself. So there are two unique parameters you need to pass one is UniqKey and you need to return a function in the parameter itself. We have an example, you can see here. In a simple syntax you can check, select const UseQuery. UseQuery is our hook and we are passing two parameters one is queryKey and query function is callback function queryKey is a brief, that is UniqKey and in a stable version or in a latest version of query you need to use array notation. With array notation we are passing you can pass multiple arrays.

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

Everything Beyond State Management in Stores with Pinia
Vue.js London Live 2021Vue.js London Live 2021
34 min
Everything Beyond State Management in Stores with Pinia
Top Content
State management is not limited to complex applications and transitioning to a store offers significant benefits. Pinia is a centralized state management solution compatible with Vue 2 and Vue 3, providing advanced devtools support and extensibility with plugins. The core API of Pinia is similar to Vuex, but with a less verbose version of stores and powerful plugins. Pinia allows for easy state inspection, error handling, and testing. It is recommended to create one file per store for better organization and Pinia offers a more efficient performance compared to V-rex.
Using useEffect Effectively
React Advanced Conference 2022React Advanced Conference 2022
30 min
Using useEffect Effectively
Top Content
Today's Talk explores the use of the useEffect hook in React development, covering topics such as fetching data, handling race conditions and cleanup, and optimizing performance. It also discusses the correct use of useEffect in React 18, the distinction between Activity Effects and Action Effects, and the potential misuse of useEffect. The Talk highlights the benefits of using useQuery or SWR for data fetching, the problems with using useEffect for initializing global singletons, and the use of state machines for handling effects. The speaker also recommends exploring the beta React docs and using tools like the stately.ai editor for visualizing state machines.
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.
Jotai Atoms Are Just Functions
React Day Berlin 2022React Day Berlin 2022
22 min
Jotai Atoms Are Just Functions
Top Content
State management in React is a highly discussed topic with many libraries and solutions. Jotai is a new library based on atoms, which represent pieces of state. Atoms in Jotai are used to define state without holding values and can be used for global, semi-global, or local states. Jotai atoms are reusable definitions that are independent from React and can be used without React in an experimental library called Jotajsx.

Workshops on related 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.
Fetch, useEffect, React Query, SWR, what else?
React Advanced Conference 2023React Advanced Conference 2023
102 min
Fetch, useEffect, React Query, SWR, what else?
Top Content
WorkshopFree
Ondrej Polesny
Ondrej Polesny
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
State Management in React with Context and Hooks
React Summit Remote Edition 2021React Summit Remote Edition 2021
71 min
State Management in React with Context and Hooks
WorkshopFree
Roy Derks
Roy Derks
A lot has changed in the world of state management in React the last few years. Where Redux used to be the main library for this, the introduction of the React Context and Hook APIs has shaken things up. No longer do you need external libraries to handle both component and global state in your applications. In this workshop you'll learn the different approaches to state management in the post-Redux era of React, all based on Hooks! And as a bonus, we'll explore two upcoming state management libraries in the React ecosystem.