React Query is a popular library that helps manage data fetching in React applications. It makes it easier to get data from a server .React Query, now part of the TanStack library, is a powerful tool that simplifies managing server-state in your React applications. It provides a comprehensive set of features for fetching, caching, synchronizing, and updating data, ensuring your app remains responsive and up-to-date
What is React Query?
React Query is a tool for React developers that simplifies the process of getting data from a server, caching it, and keeping it synchronized. It removes a lot of the repetitive and complex code that usually comes with data fetching.
Demo

Key Features
- Declarative Data Fetching: React Query uses hooks like
useQuery
to fetch data declaratively. - Automatic Caching: It caches data automatically, reducing redundant requests and improving performance.
- Background Synchronization: Keeps data fresh by refetching in the background.
- Optimistic Updates: Provides instant UI feedback during data mutations.
- Error Handling: Simplifies error management with built-in retry logic.
How React Query Works
- Setup:
- You create a
QueryClient
and provide it to your app usingQueryClientProvider
. This initializes React Query in your app.
- You create a
- Fetching Data:
- You use the
useQuery
hook to fetch data. useQuery
requires a unique key (like an ID for the data) and a function that fetches the data (e.g., a function making a fetch request to an API).
- You use the
- Automatic State Management:
useQuery
automatically handles different states for you:- Loading: When the data is being fetched.
- Error: If there’s an error while fetching data.
- Success: When the data is successfully fetched.
- Caching:
- React Query caches the data it fetches. If you request the same data again, it can serve it from the cache, making your app faster and reducing unnecessary network requests.
- Automatic Refetching:
- React Query can automatically refetch data when certain events happen, like when the window is refocused, the network reconnects, or a certain time has passed.
Installation
Install React Query in your project:
npm install @tanstack/react-query
Setting Up
Set up QueryClient
and QueryClientProvider
at the root of your application:
import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient();
function App() {
return (
<QueryClientProvider client={queryClient}>
{/* Your application components */}
</QueryClientProvider>
);
}
export default App;
Fetching Data with useQuery
The useQuery
hook is used for fetching data:
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
const fetchUsers = async () => {
const { data } = await axios.get('/api/users');
return data;
};
function Users() {
const { data, error, isLoading } = useQuery('users', fetchUsers);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
{data.map(user => (
<div key={user.id}>{user.name}</div>
))}
</div>
);
}
Mutating Data with useMutation
The useMutation
hook is used for modifying data:
import { useMutation, useQueryClient } from '@tanstack/react-query';
import axios from 'axios';
const addUser = async (user) => {
const { data } = await axios.post('/api/users', user);
return data;
};
function AddUserForm() {
const queryClient = useQueryClient();
const mutation = useMutation(addUser, {
onSuccess: () => {
queryClient.invalidateQueries('users');
},
});
const handleSubmit = (event) => {
event.preventDefault();
const user = { name: event.target.elements.name.value };
mutation.mutate(user);
};
return (
Add User
);
}
What is the difference between react query and Axios?
Feature/Aspect | React Query | Axios |
---|---|---|
Purpose | Data-fetching and state management library for React. | Promise-based HTTP client for making network requests. |
Primary Use Case | Managing server state, caching, background updates, and synchronization. | Making HTTP requests (GET, POST, PUT, DELETE, etc.). |
State Management | Automatically handles loading, error, and success states. | No built-in state management; needs to be manually handled. |
Caching | Yes, built-in caching to reduce network requests. | No, requires manual implementation. |
Automatic Refetching | Yes, on window focus, network reconnect, or specified intervals. | No, needs manual implementation. |
Pagination & Infinite Scroll | Built-in support. | No, requires manual handling. |
Background Updates | Yes, fetches data in the background. | No, requires manual handling. |
Request Interception | No, but can be used with Axios which supports it. | Yes, supports request and response interception. |
Error Handling | Built-in error handling for queries. | Manual error handling required. |
Usage | Use when you need robust data fetching with state management. | Use for straightforward HTTP requests without state management. |
Is react Query better than Redux?
React Query and Redux serve different purposes, so whether one is “better” than the other depends on the specific needs of your application. Here’s a concise comparison to help you decide which one to use:
Purpose and Use Cases
- React Query:
- Designed for managing server state (data fetched from APIs).
- Automatically handles caching, background updates, and synchronization of server data.
- Best for applications with complex data-fetching requirements and where you want automatic state updates from server data.
- Redux:
- General-purpose state management library.
- Manages global application state (not limited to server state).
- Suitable for applications with complex client-side state that needs to be shared across multiple components.
Key Differences
Aspect | React Query | Redux |
---|---|---|
Primary Focus | Server state management | Global application state management |
State Management | Handles loading, error, and success states for data fetching automatically | Requires manual state management logic |
Caching | Built-in caching and data synchronization | No built-in caching |
Data Fetching | Simplifies data fetching and updating from APIs | Needs middleware like Redux Thunk or Saga for async actions |
Setup Complexity | Easy to set up and use | More boilerplate and setup required |
Selectors & Memoization | Built-in | Requires manual implementation |
Global State Management | Limited to server state | Manages both local and global application state |
Debugging Tools | DevTools for queries | Powerful DevTools for state management |
When to Use Each
- Use React Query if:
- Your primary need is to fetch and manage server state.
- You want automatic data synchronization, caching, and background updates.
- You prefer a solution with minimal boilerplate for data fetching.
- Use Redux if:
- You need a centralized store for global state management across your application.
- Your application has complex client-side state that is not just limited to server data.
- You need fine-grained control over state changes and complex state logic.
Combined Use
You can use both React Query and Redux in the same application:
- Use React Query for server state management (data fetching and caching).
- Use Redux for global client-side state management (UI state, authentication state, etc.).
React Query and Redux are not direct competitors but are complementary tools. Choosing the right tool depends on your application’s specific requirements:
Conclusion
React Query streamlines the complexities of data fetching and updating in React applications, making it easier to manage server-state. By using React Query, developers can focus more on building features and less on handling data synchronization and state management.
When to use useQueries?
The useQueries
hook in React Query is useful when you need to run multiple queries in parallel. It allows you to fetch multiple sets of data at once, which is helpful when your component needs data from different endpoints or multiple independent queries.
Is react Query better than Redux?
For managing and synchronizing server state: React Query.
For comprehensive global state management: Redux.
Why we use useQuery in react?
useQuery
is a hook provided by React Query that simplifies the process of fetching, caching, and managing server state in React applications.
What is the difference between react query and Axios?
React Query is great for managing server state and caching in React applications.
Axios is a straightforward HTTP client for making network requests.
[…] You Want to know About React Query Click […]