reactjs

Don’t only use Fetch or Axios use this powerful asynchronous state management caching

Data from an API can be fetched, updated, and cached using React Query.

Youssef Hajjari

--

Photo by Douglas Lopes on Unsplash

Overview

According to more technical words, React Query simplifies fetching, caching, syncing, and updating server states in your React apps. It is frequently referred to as the missing data-fetching module for React.

React works well with standard data-getting techniques like the Fetch API or Axios library. They make it simple to transfer and retrieve data.

But:

what about caching or data pagination? What about deduplicating requests or automatically validating them again? Fetch and Axios are restricted to sending or obtaining data, followed by a response.

If background data updates, data caching, or memory management is necessary, the code gets more complicated. These functionalities may be quickly and simply built using React Query utilizing a straightforward code structure.

The main features of React Query are:

  • Fetch and cache data
  • Use fetched data anywhere in the app
  • Update data in the background
  • Query and Mutation retry when an error network occurs
  • Manage memory by removing data not used
  • Supports fetching from both REST and GraphQL APIs
  • Pagination, lazy loading, and infinite scroll queries
  • Typescript and React Native ready

Not only these features, but React Query also allows some configurations such as window focus re-fetching, query delay, and dependent queries.

Can cache improve user experience? 🤔

Fortunately, instead of fetching data from a remote server, there is a much faster way to get what we need. We can store the data in memory or disk to make it rendered immediately. People often call this action cache.

After caching the data, the loading phase is too short to feel. That’s cool. However, users still need to wait for data loading on their first visit. The prefetch technique can speed it up. Prefetch is a data fetch that happens before a user intentionally visits that data. Overall, we can reduce so much waiting time if using cache and some other techniques based on it.

Another advantage cache brings to us is the reliability improvement under an unstable network connection. Because of the cache, the page has already got the data it needs, regardless of the back-end server’s response quality.

Stale-While-Revalidate Strategy 🚀

That means it returns a cached value first to make the UI render instantly, while it also revalidates the data (fetch the latest data and compare the difference) and updates the state if there is any change.

1. Built-in Cache + Real-Time Experience:

When we use Fetch or Axios for data fetching in React, we usually need to show the user some loading message or spinner while data is being fetched. Using the react-query strategy, the user sees the cached (stale) data first and requests are automatically cached. Components will always be constantly updated with the most recent data, ensuring UI will always be fast and reactive

2. Auto Revalidation

assures that the user is viewing the most recent data. Therefore, even when switching between various tabs or windows, the data is always current and synchronized.

Instead of just revalidating data on focus, react-query can also revalidate data on an interval, to make sure multiple sessions will render the same components based on the data.

Finally, there’s revalidation on reconnect. In the event the user disconnects from the internet, react-query will automatically revalidate data once the user is online again.

Example Usage of react-query in React 🧑‍🔧

Step 1: Install the package

In our React app, install the package by running:

yarn add react-query

Step 2: wrap query client to your app

add the `QueryClientProvider` react-query uses to make the hooks globally available with some default settings.

import { QueryClient, QueryClientProvider } from 'react-query';const queryClient = new QueryClient();function App() {  return (   <QueryClientProvider client={queryClient}>     <Todos />   </QueryClientProvider>    );}

Step 3: Import useQuery

react-query comes has a Hook called useQuery. Let's import it into a React component like so:

import { useQuery } from 'react-query'

The useQuery Hook returns 2 values: data and error. It accepts a key as its first parameter, usually the URL or graphQL query of the request. The second parameter is a fetcher function.

An example of usage of the Hook is as follows:

const { data, error } = useQuery('/api/123', fetcher)

Step 4: Write a fetcher function

The fetcher function can be an asynchronous function, and you can use any data-fetching library to write the function. (fetch, Axios, graphql-request…)

For example, this is a fetcher function using Axios:

import axios from 'axios';
const fetcher = url => axios.get(url).then(res => res.data);

Step 5: Fetch Data

import { useQuery } from 'react-query';function App() {const { data, error, isLoading } = useQuery('users', fetcher);return (     ....
);
}

without react-query: 😒

The code above requires both useState and useEffect hooks and uses three different states to store data and determine whether the application is fetching data or already has an error response from the API. This pattern is repeated over and over again for most of your application data-fetching logic.

with react-query: 😉

Notice how in this code, we aren’t using the regular useState and useEffect hooks. This is because useQuery already has various values that we can use inside the application, such as isLoading, error response, and returned data.

You can find more details in the official documentation of react-query here.

Last but not least, there are alternative libraries that do the same thing as react-query, such as SWR or RTK Query for redux or Apollo Client for graphql.

Conclusion

In this article, we discussed some of the features why react-query and the useQuery A hook can be a great choice for data fetching in React. Its caching, pagination and auto prefetching can enhance user experience. It is lightweight and backend agnostic, which allows fetching data from any kind of API or database quickly and easily.

That’s it

I hope you enjoyed it!

Leave any questions, concerns, recommendations, or criticisms in the comments section. This motivates me to keep improving and writing on Medium

See you later! ❤️

--

--