Effortlessly Fetch and Manage Data with React Query

Integrate APIs and handle edge cases of data fetching seamlessly with React Query.
Cover image of the blog

Fetching data is a common task in any web application, and React is no exception. Whether it's retrieving information from an API or loading data from a local database, the ability to easily fetch and display data is crucial for providing a seamless user experience.

However, the process of fetching data in a React application can be repetitive and time-consuming. A lot of redundant code is often written every time a new component or feature needs data. This can lead to a cluttered and hard-to-maintain codebase.

One popular library used for fetching data in React is Axios. A promise-based HTTP client, it allows you to make HTTP requests easily. While Axios is a great tool, it can still require a significant amount of boilerplate code to set up and handle responses.

React Query, on the other hand, is a library that aims to simplify the process of fetching data in a React application. It eliminates the need to write repetitive code and offers out-of-the-box support for handling error-prone parts of data fetching, such as caching, pagination, and re-fetching. 

What’s more, is that you can also use Axios or any other popular library in conjunction with React Query to further smoothen the data fetching processes. It also offers powerful tools, such as dedicated dev tools, for managing loading states, error handling, and pagination, which can save a lot of time and improve the overall developer experience.

Getting Started with React Query

React Query is not included in the default React setup so we need to install it separately. You can do this by running the following command:

Then open the App.js file and wrap your app with the QueryClientProvider component and pass a React Query client as shown below:

The library provides us with a collection of hooks that facilitates data fetching. 

The most common is the useQuery hook and once the library is installed, you can import the useQuery hook from the “react-query” library. This hook is the primary way to fetch data in React Query.

You can use the useQuery hook in any functional component and pass it a configuration object that defines the query key, the query function, and the options.

Here's an example of how you would use the useQuery hook to fetch data from an API endpoint:

Once you've set up the query, React Query will automatically handle caching, loading states, error handling, and re-fetching. Moreover, as you can see from the code snippet above, the first argument passed to the hook is a string key, which should be unique. The second argument can be an async function where you can fetch data using any library such as Axios or the Fetch API.

Using this key we can implement complex functionalities like caching. It is worth noting that you can also pass an array of string keys.

By following these simple steps, you can get started with React Query and start simplifying the process of fetching data in your React application.

Exploring Different Features of React Query

As discussed above, React Query provides a set of hooks to handle different states of data fetching. Hooks like useMutation and useInfiniteQuery can be used for handling specific use cases like making mutations and handling infinite scrolling.

You can also customize the behavior of the query by passing options to these hooks as we’ll see below:

Handling Various States of Data

React Query provides a set of hooks that can be used to handle different states of data fetching. As shown in the example earlier, with the useQuery hook you can handle the loading, error, and success states of a query.

You can even get much finer control by passing in different options in the useQuery hook as shown below:

In the code snippet above, we have passed an object as the third parameter which tells the package to retry failed requests 10 times before displaying an error and also adds a delay of 1000ms between retries.

Global State Management

Not many people realise that React Query can also be used as a global state management solution in a React application. It provides a way to store and manage shared states across multiple components in a centralised and efficient manner.

React Query's QueryCache object is a robust tool that can be used to manage the global state in a React application. The QueryCache object is a global cache that automatically caches the results of all queries that use it. Once cached, whenever the data is requested again using the same key value, it will return the cached result instead of re-fetching, unless the cache is invalidated.

Below is an example of how you would customize your useQuery & QueryCache hooks to cache data:

Implementing Infinite Scroll

React Query provides a hook called useInfiniteQuery that can be used to handle infinite scrolling in a React application. This hook is specifically designed to handle paginated data and allows for loading more data as the user scrolls through the page.

The useInfiniteQuery hook takes a similar configuration as the useQuery hook but also takes an additional getFetchMore function that tells React Query how to fetch the next page of data.

Here's an example of how you would use the useInfiniteQuery hook to handle infinite scrolling:

In this example, the useInfiniteQuery hook is used to fetch the data from an API endpoint with a page parameter. The "fetchMore" function is used to load the next page of data and the "canFetchMore" property is used to check if there are more pages to load.

Dependent Queries

A dependent query is a query that depends on the result of another query, and it only gets executed when the parent query has been successfully resolved. 

This can be useful when you need to fetch additional data based on the result of a previous query, for example, fetching details of an item based on the authentication state of the user.

You can handle dependent queries as shown below:

As you can see, using the “enabled” property, we can control if and when the query can be executed. Whenever the “enabled” property is set to true it will start fetching the data.

Which Projects Can Benefit From This Package?

React Query is a powerful library that can benefit a wide range of projects, especially those that involve fetching data from an API. The library is designed to simplify the process of fetching data in a React application, making it more efficient and reducing the amount of redundant code while allowing developers to quickly handle different states of data fetching.

Applications such as e-commerce websites, social media platforms, and content management systems require a lot of data to be fetched and displayed to the user and these projects can benefit greatly from this package.

Another use case for React Query is in building real-time applications, such as chat and collaboration tools, that require frequent updates of data. React Query's caching and re-fetching features allow for efficient updates of data, without the need for unnecessary network requests.

While React Query facilitates data fetching and can speed up API integrations, using the plugin you can generate pixel-perfect frontend code that you can easily extend with this package. In short, using and React Query you can ship products with API integrations 5-10x faster.

If you want to learn more about how to convert your Figma or Adobe XD designs to React, React Native, HTML/CSS, Nextjs, and more, check out our docs.

Keep your loco mode on!
Stay updated on the latest Locofy announcements and product updates

© 2024, Locofy Pte Ltd. All Rights Reserved.