How to Use React Query for Data Fetching
React Query is a powerful library that simplifies data fetching and state management in React applications. It provides an easy-to-use API that streamlines the process of fetching, caching, and synchronizing data from various sources. In this article, we will explore how to use React Query for data fetching effectively.
Installing React Query
To get started with React Query, you first need to install the library in your React application. Use npm or yarn to add React Query to your project:
npm install react-query
or
yarn add react-query
Setting Up the Query Client
After installing React Query, you need to set up a Query Client. The Query Client is responsible for managing all your queries and caches. You can create an instance of Query Client and provide it to your application via the QueryClientProvider
:
import React from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
const queryClient = new QueryClient();
function App() {
return (
...
);
}
Creating a Simple Query
To fetch data using React Query, you can use the useQuery
hook. This hook accepts a unique query key and an asynchronous function that fetches the data. Here’s a simple example:
import { useQuery } from 'react-query';
const fetchUsers = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
};
function Users() {
const { data, error, isLoading } = useQuery('users', fetchUsers);
if (isLoading) return Loading...
;
if (error) return Error: {error.message}
;
return (
{data.map(user => (
- {user.name}
))}
);
}
Handling Loading and Error States
React Query provides you with built-in state handling for loading and error states. You can conditionally render UI based on these states, as shown in the previous example. The isLoading
and error
return values from useQuery
can be used to enhance user experience.
Refetching Data
React Query allows you to easily refetch data in various scenarios. For instance, you can set up refetching on window focus, which is useful for keeping data fresh. This can be done using the refetchOnWindowFocus
option:
const { data, error, isLoading } = useQuery('users', fetchUsers, {
refetchOnWindowFocus: true,
});
Mutations in React Query
React Query also supports creating, updating, or deleting data through mutations using the useMutation
hook. Here’s an example of how to add a new user:
import { useMutation, useQueryClient } from 'react-query';
const addUser = async (newUser) => {
const response = await fetch('https://jsonplaceholder.typicode.com/users', {
method: 'POST',
body: JSON.stringify(newUser),
headers: {
'Content-Type': 'application/json'
},
});
return response.json();
};
function AddUser() {
const queryClient = useQueryClient();
const mutation = useMutation(addUser, {
onSuccess: () => {
// Invalidate and refetch
queryClient.invalidateQueries('users');
},
});
const handleAddUser = () => {
mutation.mutate({ name: 'New User' });
};
return ;
}
Conclusion
Using React Query for data fetching makes managing your application's server state straightforward and efficient. It handles caching, background fetching, and synchronization with minimal setup, making it an excellent choice for modern React applications. By incorporating React Query into your projects, you can enhance user experiences while streamlining data management.
For more advanced features like pagination, query invalid