What is React Query? Why should you use React Query?

Tram Ho

rq-logo.png

Why use react-query?

The ways of managing and dividing local and global state above are still working well and are relatively common for current React projects.

But there is a better way of separating client state and server state. This is an idea from react-query, a pretty hot library recently that everyone talks about.

Previously when we wanted to fetch data from the server, we could use window.fetch or axios, but neither of these methods handle caching data. Because there is often a need that we want to cache the server’s data on the client (for faster retrieval when needed, and no more API calls). And we often handle it ourselves (somewhat quite tedious and cause many problems) or use other libraries. With react-query, it not only fetches data but also handles caching, syncing and updating data between client and server. And there are many more benefits here .

Thanks to react query, we have realized that there should be a difference between server state and client state.

  • Server state is the data stored on the server side and we use the API to get it on the client (React web). For example userInfo, listItems, propertyDetail, ….
  • Client state (UI state) is the data that only exists in React and is not saved to the server such as isModalOpen, isLoading, status variables, etc. These data will be lost when we reload the page.

We could be wrong to combine these two states together on Redux or Context. The management, updating and synchronization or cache of data from the server should be separated and handled better.

Some salient features of server state are:

  • It is located on the server and you cannot control it directly.
  • Need an async request to get and update
  • It can be changed by someone you don’t know
  • It gets stale or outdated during the use of the app

With react-query we will manage server state separately and more efficiently. Caching makes the app run faster and smoother. For example, you call the API /posts to get all posts when the page starts to load, then click to see the details of each post (detail page). When you press the Back button to return to the posts page, by default you will see the data already available from the cache and the user will see the data immediately (no need to wait for an API call like using axios or window.fetch). The special thing is that now react-query also calls the underlying API (background refetch) to update the posts automatically for you.

To summarize some of the benefits of react-query

  • Caching data for API
  • Limit calling multiple duplicate requests
  • Automatically update the data of the API below, keeping the data fresh and in sync with the server
  • Pagination and lazy loading
  • Control data when it is old, can be recalled easily
  • Help increase UX experience for web apps with “instant” data

Let’s start with React-Query

The main benefits that React-Query gives us:

  • Window focus refetching : when the user leaves your app’s tab, React Query will mark the data as “stale” and relearn it when he or she comes back.
  • Request retry : you can set the number of retries for any request to combat random errors.
  • Prefetching : if your app needs new data after an update request, you can prefetch the query with a specific key and React Query will update it in the background.
  • Optimize Updates : when you edit or delete an item in a list, you can give an optimistic update to the list.

Below is the basic configuration to start using React-Query

Moving on, let’s say we have a fetching function that uses Axios to get the posts data

Combining our fetch function with React-Query will be extremely simple

By calling the React-query hook and retrieving the data-binding variables that React-Query previously specified, it is completely easy to use and accessible to us.

Fetching data is now better

Why is it better than normal way of fetching data with useEffect . When we query with the same key defined in useQuery, React-Query immediately returns previously fetched data and fetches new data.

When the second dataset is the same as the first, the React Query will keep both as a reference without forcing a reload. It’s a huge improvement to the user experience.

How Hooks Work

You already know how to fetch data easily with React-Query. Now learn how to update it.

React Query has a useMutation hook that you can use to update/create/delete data. useMutation gives you access to the mutate function to which we can pass the necessary arguments. It then returns information about the state of our API call. Status can be:

  • idle : for idle or new/reset state
  • Loading : for a currently running mutation,
  • error : When an error occurs
  • success : When everything is done and the data is ready.

You can access the state information from the state variable, or for those who prefer boolean state, they can access it through the following variables.

  • isIdle
  • isLoading
  • isError
  • isSuccess

As you can see, it is very easy to use. And there are many choices for you when using useMutation React Query can become one of your most powerful developer tools.

The real power lies behind?

What happens when a device goes offline for a while while sending data? React Query has a solution for that!

Use Request Retry

You can pass the try option with the number of times the query will retry the mutation after reconnecting.

Query Client helps a lot with caching

The function is packed with many methods to help you deal with cache caching.

  • invalidateQueries method marks a query with the given key as invalid to make the React Query fetch that data again. You can use that method in the useMutation hook after a successful update (example below).
  • setQueryData is used for improving cached data updates
  • prefetchQuery method helps you to re-fetch some data before it is needed and render it with useQuery. If you know when the user needs that data, using this method is a way of fetching data that greatly improves the user experience.
  • clear simply clears all cached caches

To use these methods, you will need to import the useQueryClient hook from React-Query. Then assign it to a variable as const queryClient = useQueryClient and call the methods inside it by calling a regular object.

useMutation hook options

In most cases you will use Query Client methods inside hooks options. Let’s take a look at them

  • onMutate This function works before useMutation. It is quite useful when you want to run your updates on the local cache and update the UI data before the mutation occurs on the server.
  • onSuccess The function that runs when calling the mutation successfully. Query with predefined key and will be fetched back in your application background. You can see an example below

  • onError Will occur when the mutation calling process has an error. It’s very common to set cache to previous data when something goes wrong
Share the news now

Source : Viblo