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.

16 min
23 Oct, 2023

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.

Available in Español

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.

3. React Query: Query, Mutation, and Caching

Short description:

There is a query function that helps useQuery hooks to fetch data. The useQuery hook is used to fetch users asynchronously. useMutation allows updating and changing data from the server. It returns an object with properties fetched from the API. Query caching is used to speed up data fetching by saving previous data. StaleTime determines when a query result is considered stale.

There is a query function which is a callback function. Which helps useQuery hooks to get or fetch the data at certain point. So this is how you can simply, there is a syntax and simply you need to pass two parameters queryKey and query function. This is an example which is a small example like how you can use a useQuery. By using two key identifiers. Identify each query.

So here is a simple request, fetch users or fetching some users using simple asynchronous call and what we are doing is, we are getting the data and we are using useQuery hooks here and we are passing key users, we want users from the data itself and we are fetching users, which is this call which is callback call. And based on that we are mapping all the user data here. So this is a very simple example for how we can use a useQuery

Second one is useMutation. UseMutation is allow a react query to update or change the data from the server itself. You can update and use that modified data into your app. So useMutation hooks is helping to create, update and delete data from the API input itself. You don't need to go to ask your database engineer or go to database and delete and then you can check. You can simply use mutation and based on API input you can delete, update or create any changes in your data. UseMutation hooks requires at least one option. You can see what are the options you can pass. It's a simple syntax you can look.

So const mutation, useMutation is a hooks and mutation function we are simply passing any function here. useMutation hooks basically return an object, an object can contain several properties which we are fetching from the API itself. This is a simple example. We are adding the user, using the useMutation in the API. This is the API end point. We are using the post method and simply we are passing the body, what are the users we need to update. We are using a mutate basically it executes our functions we are adding this user, we want to delete, you can use delete or if you want to just update you can update. Query caching is another hook which is a react query itself. Query caching is when you are doing useQuery or any kind of other query parameter when you are fetching the data from the remote servers or API or database. To speed up that thing you need to save that data, previous data to just not fetch and not do any kind of request because if you do request again and again it costs a server it is not a best practice so for that mostly people use a caching and query caching is a built function of React. There are 2 default properties which you can use any option you can use is staleTime and CacheTime. So how that works is StaleTime basically determine the time which takes query result to be considered as stale. If you can see we are just querying QSquery key is users function are GETuser and we are putting CacheTime is 500.

4. Cache Time and Query Invalidation

Short description:

This section discusses cache time and query invalidation in React Query. CacheTime determines how long data remains cached, while query invalidation allows you to mark specific queries as stale. React Query provides hooks like useQueryClient and queryClient.invalidQueries to handle invalidation. The library offers efficient state management and features built-in caching and memory optimization. With React Query, developers can significantly reduce code complexity and optimize performance.

This data can remain for 5 seconds when you are doing API. Calling or fetching the data Then if we put a CacheTime is basically how long you need to catch that result. So if you think our data will be updated every minute or every 30 minute or every 40 minute. Like everyday. You can put timer here. CacheTime will catch your data for whatever the period or whatever the minutes you apply into this.

Then lets move to query invalidation. So basically Query Invalidation method is to use a specific query and a STALE. In STALE you can mark the STALE time which we previously saw in QueryCache If you want to overwrite all the STALE configuration to be used in a real query, this hook is you can use. It's basically used in some of the conditions for that you need to use invalid query methods. So how you can use is simply you can import QueryClient as useQueryClient and basically queryClient.invalidQueries and invalidQuery is basically whatever the key you want to pass in a use query that basically help you to only invalid query like you don't want more variables or subkeys and if you pass like set true option, invalid method is useful to just pass invalid query data. There is like this two method.

So this function is receive each query instant from the query catch and its allow you to return true or false values and based on that you can invalidate the query data. So React query is the robust library that allows you for efficient state management. It make you use of React hooks or use query or use mutation. You can modify data based on API point or server. In addition there are lot of features in built catching mechanism or memory optimization, memory catching. You can catch the data, steal the data and using the react query you can the developer can significantly reduce the code complexity which we love. One of the example I can give is VR building a ONE app which is a web 3 app but there are huge data coming from the node itself and we want to use that query data and how we can optimize that query we are confused and then we use react query and we optimize more than like 1000 plus lines in the code itself to optimize lot of logic we implement catching and all and using that we are serving a million of user right now for a client itself. It's not a build product but client product and how we can optimize that product using a react query, that's one of the great example we put at the production as a team.

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

Vue.js London Live 2021Vue.js London Live 2021
34 min
Everything Beyond State Management in Stores with Pinia
Top Content
When we think about Vuex, Pinia, or stores in general we often think about state management and the Flux patterns but not only do stores not always follow the Flux pattern, there is so much more about stores that make them worth using! Plugins, Devtools, server-side rendering, TypeScript integrations... Let's dive into everything beyond state management with Pinia with practical examples about plugins and Devtools to get the most out of your stores.
React Advanced Conference 2022React Advanced Conference 2022
30 min
Using useEffect Effectively
Top Content
Can useEffect affect your codebase negatively? From fetching data to fighting with imperative APIs, side effects are one of the biggest sources of frustration in web app development. And let’s be honest, putting everything in useEffect hooks doesn’t help much. In this talk, we'll demystify the useEffect hook and get a better understanding of when (and when not) to use it, as well as discover how declarative effects can make effect management more maintainable in even the most complex React apps.
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
An increasing amount of data in our React applications is coming from remote and asynchronous sources and, even worse, continues to masquerade as "global state". In this talk, you'll get the lowdown on why most of your "global state" isn't really state at all and how React Query can help you fetch, cache and manage your asynchronous data with a fraction of the effort and code that you're used to.
React Day Berlin 2022React Day Berlin 2022
22 min
Jotai Atoms Are Just Functions
Top Content
Jotai is a state management library. We have been developing it primarily for React, but it's conceptually not tied to React. It this talk, we will see how Jotai atoms work and learn about the mental model we should have. Atoms are framework-agnostic abstraction to represent states, and they are basically just functions. Understanding the atom abstraction will help designing and implementing states in your applications with Jotai
JSNation 2022JSNation 2022
27 min
Announcing Starbeam: Universal Reactivity
Starbeam is a library for building reactive data systems that integrate natively with UI frameworks such as React, Vue, Svelte or Ember. In this talk, Yehuda will announce Starbeam. He will cover the motivation for the library, and then get into the details of how Starbeam reactivity works, and most importantly, how you can use it to build reactive libraries today that will work natively in any UI framework. If you're really adventurous, he will also talk about how you could use Starbeam in an existing app using your framework of choice and talk about the benefits of using Starbeam as the state management system in your application.
React Advanced Conference 2023React Advanced Conference 2023
28 min
A Practical Guide for Migrating to Server Components
Server Components are the hot new thing, but so far much of the discourse around them has been abstract. Let's change that. This talk will focus on the practical side of things, providing a roadmap to navigate the migration journey. Starting from an app using the older Next.js pages router and React Query, we’ll break this journey down into a set of actionable, incremental steps, stopping only when we have something shippable that’s clearly superior to what we began with. We’ll also discuss next steps and strategies for gradually embracing more aspects of this transformative paradigm.

Workshops on related topic

React Summit 2020React Summit 2020
96 min
Rethinking Server State with React Query
Top Content
Featured Workshop
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.
React Summit Remote Edition 2021React Summit Remote Edition 2021
71 min
State Management in React with Context and Hooks
WorkshopFree
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.