Lang
Blog

React Query — A State Management Library for React Applications

ByPayal Mittal
December 15th . 5 min read
React Query — A State Management Library for React Applications

Most of the developers find the state management in React applications a great pain and end up using general-purpose state management libraries like Redux, MobX, or Flux. These libraries are a good choice for it but they add more complexity to the code.

Today, we are going to discuss another alternative (and far better than others), which is React Query. In this blog, we will see how it is different from other conventional state management libraries. But first, let’s check out what it is-

What is React Query?

React Query is a state management tool and used for fetching, caching, synchronizing, and updating your remote asynchronous data in the server state React applications without having anything to do with the ‘global state’.

It reduces the code amount to a surprisingly large extent by providing two simple and important hooks- useQuery and useMutation. These hooks are used to perform queries and mutations respectively.

React Query is also known as the ‘missing-data fetching’ library. Just like the query languages, React Query is based upon three core concepts- Queries, Mutations, Query Invalidation.

It is fully-featured and comes with a stack of devtools. The long list of features is given in the subsequent section-

Why React Query??

The conventional state management libraries work well for the client state but do not fare well when it comes to the server or async state. The blame, entirely, goes to the server state which is very different as well as difficult to deal with.

To start with-

  • It requires async APIs for data fetching
  • It can easily go out-of-date, if not careful
  • Caching (the most tricky part of all)

However, when you come to know about it, even more difficulties you face, such as- updating the out-of-date data, caching, lazy loading, performance optimization, memory management, garbage collection, query results memorizing with structural sharing, etc. The list has not ended. There are so many more challenges that we have to tackle with server state.

But thanks to React Query! It best manages the server state, tackles all these challenges, overcomes them, and provides control over your app data.

👉It replaces the multiple complicated and complex code lines with a few logical and simple ones.

👉 Increases memory performance

👉 Enable lazy loading and pagination- improving overall performance

Other features are given here-

  • Auto caching and re-fetching
  • View cache in real-time
  • Backend agnostic data fetching
  • Window focus re-fetching
  • Query Key Serialization
  • Remove and re-fetch queries manually
  • Automatic garbage collection
  • Request cancellation
  • Multi-layer caching
  • Mutation Hooks
  • Dedicated React Query DevTools

I’m going to explain a couple of these features here-

Lazy Loading

While React Query loads the next query loads, it continues to see the existing query’s data. This is an important property, which other libraries do not possess and end up rendering a hard loading state for new queries.

Partial Query Matching

Due to the query key serialization property of React Query, you can manipulate and match a group of variable queries without having to know each one individually. You can target specific queries by using their nested properties or even by applying a filter to separate out those queries that match your criteria.

Installation

You can easily install React Query with npm or yarn, via a simple command-

$ npm i react-query
#or
$ yarn add react-query

One of the most welcoming parts of React Query is that it comes with a set of dedicated devtools. If you want your journey with React Query to be a fun and amazing experience, you’d definitely want to get these devtools. Here’s what you need to do-

import { ReactQueryDevtools } from 'react-query/devtools'

Now, let’s get a closer look at the two React Query hooks

useQuery Hook

The useQuery hook is a function that is used to create and run new queries. It takes a unique query key every time it raises a query and a query function to resolve the data.

The unique query key is internally converted into an array and used for caching, sharing, and re-fetching queries in the application.

import { useQuery } from 'react-query'
function App() {
  const { status, data, error, isFetching } = useQuery('key', asynchrousFunction)
}

The query results return a few states indicating the current state of the query, e.g., isLoading, isIdle, isFetchhing, isError, or isSuccess. Each of these states tells us whether the query is loading, disabled, successful, or encountered an error. The isFetching indicates whether the query is re-fetching the data or not.

useMutation Hook

Mutations in React Query are used for creating/updating/deleting data or perform server side-effects.

The useMutation hook is used for this very same purpose, i.e., to perform mutations.

It uses an asynchronous function to update your data between different requests and returns a mutate function that triggers the mutations.

const mutation = useMutation(newTodo => axios.post(‘/todods’, newTodo))

Like queries, the state of mutation can be determined by some primary states like isLoading, isIdle, isError, isFetching or isSuccess.

The mutate function plays a very important role because it can be used to trigger certain specific mutations when used with certain specific options like onSuccess, onSubmit, or onError.

This was a brief intro to this fantastic library; you can know more about it here.

React Query is not much popular but deserves your attention. After reading this blog, I hope you’ll give it a try.

Thanks for reading!!

Share:
0
+0