API fetching using React Query in ReactJS

Abhijeet kumar
2 min readJun 21, 2023

--

React Query is a popular package that provides an efficient and declarative way to manage and fetch data in React applications. It simplifies common data-fetching tasks, such as making API requests, caching, data synchronization, and handling loading and error states.

To use React Query, you need to install it first. You can do this by running the following command in your project directory:

npm install react-query

Once React Query is installed, you can start using it in your React components.

  1. Import React Query:
import { useQuery } from 'react-query';

2. Define a query function:

async function fetchUserData() {
const response = await fetch('/api/user');
const data = await response.json();
return data;
}

The fetchUserData function is an example of a function that fetches user data from an API. You can modify it to suit your specific use case.

3. Use the useQuery hook to fetch and manage data:

function UserProfile() {
const { isLoading, isError, data, error } = useQuery('userData', fetchUserData);

if (isLoading) {
return <div>Loading...</div>;
}

if (isError) {
return <div>Error: {error.message}</div>;
}

return (
<div>
<h1>User Profile</h1>
<p>Name: {data.name}</p>
<p>Email: {data.email}</p>
</div>
);
}

In this example, the useQuery hook takes two arguments: the query key and the query function. The query key is a unique identifier for the query, and it can be any string or array of strings. In this case, we used 'userData' as the query key. The query function, fetchUserData, is called to fetch the data.

The useQuery hook returns an object with several properties:

  • isLoading indicates whether the data is still being fetched.
  • isError indicates whether an error occurred during the fetch.
  • data contains the fetched data.
  • error contains the error object if an error occurred.

Based on the state of these properties, you can conditionally render different components. In the example above, we render a loading message while the data is being fetched and an error message if an error occurs. Once the data is fetched successfully, we render the user profile information.

React Query handles caching and automatically updates the data when needed. It also provides additional features like automatic refetching, pagination, and optimistic updates.

You can customize the behavior of the useQuery hook by passing various options as the third argument. These options allow you to control the cache behavior, polling intervals, and more.

React Query also provides other hooks like useMutation for handling data mutations (e.g., POST, PUT requests) and useInfiniteQuery for handling infinite scrolling or pagination.

This is a brief overview of using React Query for data fetching in a React application. The library offers more advanced features and customization options, so be sure to refer to the official React Query documentation for more in-depth usage examples and details.

--

--

No responses yet