A quick guide to react-query

Sean Marcus
5 min readDec 9, 2022

--

React-query is a library for React that allows developers to easily manage data in their applications by providing features for fetching, caching, and updating asynchronous data. It is designed to make it easy to fetch and manage data in your React components, without having to worry about things like optimizing requests or updating the UI when data changes. With react-query, you can declaratively specify what data your components need, and the library will automatically fetch and manage that data for you, freeing you up to focus on building your application.

Get Requests

To make a simple GET request in react-query, you can use the useQuery hook in a React component. Here's an example of how you might use it to fetch data from an API:

import { useQuery } from 'react-query';
function MyComponent() {
const { data, isLoading, error } = useQuery('my-data-key', async () => {
const response = await fetch('https://my-api.com/data');
return response.json();
});
if (isLoading) return <p>Loading data...</p>;
if (error) return <p>An error occurred: {error.message}</p>;
return <p>Data: {data}</p>;
}

This code will automatically fetch the data from the API when the component is rendered, and will update the UI with the data when it is available. If the data has already been fetched, it will be retrieved from a cache so that the API is not needlessly queried again.

The benefits of setting up a GET request in react-query like this are that it allows you to declaratively specify what data your components need, and the library will take care of fetching and managing that data for you. This can make it easier to manage data in your application, and can help improve the performance of your application by reducing the number of unnecessary network requests.

POST and PUT Requests — Mutations

To mutate data in a database using react-query, you can use the useMutation hook in a React component. This hook allows you to specify a function that will be called when the mutation should be performed, and it will automatically handle updating the cache and updating the UI when the mutation is complete.

Here’s an example of how you might use useMutation to update data in a database:

import { useMutation } from 'react-query';
function MyComponent() {
const [mutate, { isLoading, error }] = useMutation(async (data) => {
const response = await fetch('https://my-api.com/update-data', {
method: 'POST',
body: JSON.stringify(data),
});
return response.json();
});
const onClick = () => {
mutate({ id: 123, name: 'John Doe' });
};
return (
<button onClick={onClick}>
{isLoading ? 'Updating...' : 'Update data'}
</button>
);
}

In this example, the mutate function is called when the button is clicked, and it will perform the mutation by sending a POST request to the API with the new data. When the mutation is complete, the cache will be automatically updated, and the UI will be updated to reflect the changes.

Using useMutation in this way can make it easier to manage data mutations in your application, and can help ensure that your application's data and UI are always in sync.

React Query and Typescript

To use TypeScript with react-query, you will need to install the @types/react-query package, which provides TypeScript definitions for the react-query library. Once you have installed this package, you can import the useQuery and useMutation hooks from the react-query module, and TypeScript will be able to infer the types of the data you are working with.

Here’s an example of how you might use TypeScript with react-query to fetch and mutate data:

import { useQuery, useMutation } from 'react-query';
function MyComponent() {
// Infer the type of the data being fetched based on the return type of the async function
const { data, isLoading, error } = useQuery<MyDataType>('my-data-key', async () => {
const response = await fetch('https://my-api.com/data');
return response.json();
});
// Infer the type of the data being mutated based on the type of the argument to the async function
const [mutate, { isLoading, error }] = useMutation<MyDataType>(async (data) => {
const response = await fetch('https://my-api.com/update-data', {
method: 'POST',
body: JSON.stringify(data),
});
return response.json();
});
return (
<div>
{isLoading ? (
<p>Loading data...</p>
) : (
<p>Data: {data}</p>
)}
<button onClick={() => mutate(data)}>
{isLoading ? 'Updating...' : 'Update data'}
</button>
</div>
);
}

In this example, the useQuery and useMutation hooks are used with generic type arguments to specify the types of the data being fetched and mutated. This allows TypeScript to provide type checking and type inference for the data in your application, which can help prevent type errors and make it easier to work with react-query in a type-safe manner.

The react-query library provides a number of benefits for managing data in React applications. Some of the key benefits of using react-query include:

  • Declarative data fetching: With react-query, you can declaratively specify what data your components need, and the library will automatically fetch and manage that data for you. This can make it easier to manage data in your application and can help improve the performance of your application by reducing the number of unnecessary network requests.
  • Automatic caching: react-query automatically caches data that has been fetched, so that subsequent requests for the same data can be served from the cache instead of re-fetching the data from the network. This can help improve the performance of your application by reducing the amount of network traffic and can help ensure that your application always has access to the data it needs.
  • Optimized data updates: react-query automatically optimizes data updates to ensure that the minimum amount of work is done to update the UI when data changes. This can help improve the performance of your application and can help ensure that your application always has the most up-to-date data.
  • Support for TypeScript: react-query provides built-in support for TypeScript, allowing you to use type checking and type inference with the library. This can help prevent type errors and can make it easier to work with react-query in a type-safe manner.

--

--

Sean Marcus
Sean Marcus

No responses yet