What Is React Query? A Complete React Query Tutorial (Why It’s a Superpower)
On this page
Introduction
The useEffect hook, which requires programmers to define a function to call the API, a loading state, an error state, and so on, is the conventional method of calling an API in ReactJS. The issue is that programmers can't manage everything as effectively as they could.
There are a lot of things related to the API call that we left during development, which caused unpredictable bugs in the production phase, and we have to resolve them manually.
I personally faced this issue during my project journey, where I forgot to cache the API data; calling the API multiple times led to server load. Just imagine how many pointless API calls we would make on the server and how overloaded it would become if a lot of people visited our website.
Then I found React Query and started incorporating it into my projects. It altered my approach to implementing APIs in React apps; it cuts down on a lot of code lines, improves code quality, and makes components easier to manage. Let's discuss what this React Query is and how to integrate it into our ReactJS application.
What is React Query?
React Query is an npm library provided by Tanstack. It is a widely used library for handling data fetching, caching, error, loading, and server state in ReactJS applications. The best part is we can use it directly with our REST and GraphQL API.
It is a bit confusing, but believe me, as you read further in this React Query tutorial, you will get to understand.
Why Use React Query Instead of useEffect?
Before knowing React Query, we should know why we need it and what the reason is, and then we can understand why we use it.
In the past, we simply imported the useEffect and created a state where we would store the API data when we needed to call an API in our frontend application. The loading state, error state, and so on had to be created. This method of development is still used by the majority of people.
import { useEffect, useState } from "react";
function App() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((res) => {
if (!res.ok) throw new Error("Failed to fetch");
return res.json();
})
.then((json) => setData(json))
.catch((err) => setError(err.message))
.finally(() => setLoading(false));
}, []);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return (
<div>
<h3>{data.title}</h3>
<p>{data.body}</p>
</div>
);
}
export default App;
In the above example, you can see how we are calling an API in traditional fashion. Just think, when we work on a production-grade application, we have to call multiple APIs in the same component, and at some point the code looks very messy and unmanageable.
To solve it, we can create a custom hook where we will encapsulate the logic regarding the API call. and now use that hook anywhere in your component. Take a look at the example below.
// src/hook/useGetApi.js
import { useEffect, useState } from "react";
function useGetApi(url, options = {}) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
let isMounted = true;
const fetchData = async () => {
setLoading(true);
setError(null);
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`Error: ${response.status}`);
}
const result = await response.json();
if (isMounted) {
setData(result);
}
} catch (err) {
if (isMounted) {
setError(err.message);
}
} finally {
if (isMounted) {
setLoading(false);
}
}
};
fetchData();
return () => {
isMounted = false;
};
}, [url]);
return { data, loading, error };
}
export default useApi;
// src/component/Users.jsx
function Users() {
const { data, loading, error } = useGetApi("/api/users");
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return (
<ul>
{data.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Did you see the above hook? How we are calling the API: this is for the GET request you can create for other API methods (POST, PUT, etc.). Somehow we optimized it more than earlier, but still we have a few things missing, like data caching, request deduplication, server state, and many other things.
If we want that, we can create all the things, but that will be a time-consuming process and not preferable on a production-grade application.
Instead of doing it the custom way, we can use the npm library. This is where React Query comes into the picture, giving us incredible features and streamlining development. Let's see how we can utilize it in our application.
React query Installation
Installation is very straightforward; we just need the latest version of Node, and we can use any package manager (NPM, Yarn, or Pnpm).
NPM
npm i @tanstack/react-query
Yarn
yarn add @tanstack/react-query
Pnpm
pnpm add @tanstack/react-query
By using the above command, React Query will be installed in our application, and then we can utilize it.
Now after installation we have to create a provider that wraps our whole app; it is a very important step where we define our query client, which will be used by our app to store data coming from the API call.
It's similar to React context in that any child component can use a provider that we create and pass all the data from. Let's look at an example.
// src/providers/query-provider.jsx
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
const queryClient = new QueryClient();
const QueryProvider = ({ children }) => {
return (
<QueryClientProvider client={queryClient}>
{children}
</QueryClientProvider>
);
};
export default QueryProvider;
Now import it and wrap your application. I am taking an example of the Next.js application where we have layout.jsx a file; it is the root layout. Inside it we will wrap our app like this.
// src/app/layout.jsx
import { Inter } from "next/font/google";
import "./globals.css";
import QueryProvider from "@/providers/query-provider";
const interMono = Inter({
variable: "--font-inter-mono",
subsets: ["latin"],
weight: ["100", "200", "300", "400", "500", "600", "700", "800", "900"],
});
export const metadata = {
title: "My React Query App",
description: "",
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body
className={`${interMono.variable} antialiased font-sans`}
>
<QueryProvider>{children}</QueryProvider>
</body>
</html>
);
}
React Query provides these four basic components
- Queries to handle fetching data with the help of
useQueryhook. - Mutations, to handle the creation, updating, or deletion of delete data on server with the help of
useMutation - Query caching, It helps to cache the API data in memory.
- Query invalidation helps to take the latest data from the server.
Queries and useQuery
Queries are used in React Query to fetch data from the server. In simple terms, it is used for the GET request. In React.js or any framework of React.js, we will use useQuery React Hook to define it. Let's see an example of it.
// src/utils/api.js
const fetchUsers = async () => {
const response = await fetch("/api/users");
if (!response.ok) {
throw new Error("Failed to fetch users");
}
return response.json();
};
// src/component/Users.jsx
import { useQuery } from "@tanstack/react-query";
function Users() {
const { data, isLoading, error } = useQuery({
queryKey: ["users"],
queryFn: fetchUsers,
});
if (isLoading) return <p>Loading...</p>;
if (error) return <p>{error.message}</p>;
return (
<ul>
{data.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
So, as you can see in the above example, we are fetching the user list from the server. For that, we have a function fetchUser, which is used to call the API, and in the users component, we import useQuery a hook. Below it, it takes two things one is the query key, and the second is the queryFn.
These two things are the most important things of any query in React Query. How? Let's try to understand.
The queryKey is the unique value we have to provide when we initialize it based on that React query cache, the data, revalidation, and other things. It's like a dependency array, like we pass in useEffect, as it will change. React Query will call the API and fetch the data and cache that against the new query key.
queryFn is an async function; yes, it is important; it should return the promise; it is responsible for calling the API. Then React Query handles all the things internally.
Now useQuery returns multiple things, like data that is coming from the API. provide other state loading errors, which we can use to handle other states of the UI; it is the most used thing, and it also returns other properties, which you can also explore.
Note: The query function is a function that is used to fetch data inside that you can use fetch, axios, or any other utility that helps you to get data.
Mutations—Updating Server Data
Mutations in React Query are used to save the data in the DB; basically, it is used whenever we can call POST, PUT, and PATCH APIs. These methods of HTTP requests are used to write or update something on the DB side.
Mutations provide a mutation function, which we call explicitly on any event like a button click, form submit, etc. To implement it, React Query provides the useMutation hook. Let's see an example below.
// src/utils/api.js
const createUser = async (newUser) => {
const response = await fetch("/api/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newUser),
});
if (!response.ok) {
throw new Error("Failed to create user");
}
return response.json();
};
// src/components/add-user.jsx
import { useMutation } from "@tanstack/react-query";
function AddUser() {
const mutation = useMutation({
mutationFn: createUser,
});
const handleSubmit = () => {
mutation.mutate({
name: "John Doe",
email: "john@example.com",
});
};
return (
<div>
<button onClick={handleSubmit} disabled={mutation.isPending}>
Add User
</button>
{mutation.isPending && <p>Saving...</p>}
{mutation.isError && <p>{mutation.error.message}</p>}
{mutation.isSuccess && <p>User created successfully!</p>}
</div>
);
}
export default AddUser;
It is similar to useQuery; here we also need to define an API function, which is responsible for calling an API. Next, we provide mutationFn and invoke the useMutation hook in the Add user component.
Like useQuerystates, it provides data and other states, which we can use to handle different states on the UI. One more important thing: it returns a mutation function, which is used to call an API. You can see we are calling it inside the handleSubmit function.
React query Caching and Invalidation
How Query Caching Works in React Query
React Query automatically caches API responses to avoid unnecessary network requests and improve performance. When a query is executed, React Query stores the returned data in memory. If the same query is requested again, React Query first checks the cache and returns the cached data instead of calling the API again. This makes React Query highly efficient, especially in applications where the same data is used across multiple components.
The caching behavior is controlled using a query key, which uniquely identifies each query in the cache.
What Is a Query Key in React Query?
A query key is a unique identifier used by React Query to store, retrieve, and manage cached data. It is usually an array that represents the data being fetched. If the query key changes, React Query treats it as a new query and refetches fresh data from the server.
// src/utils/api.js
const fetchUsers = async () => {
const response = await fetch("/api/users");
if (!response.ok) {
throw new Error("Failed to fetch users");
}
return response.json();
};
// src/components/Users.jsx
import { useQuery } from "@tanstack/react-query";
function Users() {
const { data, isLoading, error } = useQuery({
queryKey: ["users"],
queryFn: fetchUsers,
});
if (isLoading) return <p>Loading...</p>;
if (error) return <p>{error.message}</p>;
return (
<ul>
{data.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
In this example, the query key ["users"] tells React Query to cache the response under that key. If another component uses the same query key, React Query will reuse the cached data instead of making a new API request.
What Is Query Invalidation in React Query?
Query invalidation is the process of marking cached data as stale when the server data changes. For example, after creating, updating, or deleting a user, the previously cached users list may no longer be accurate. React Query provides the invalidateQueries method to handle this automatically.
When a query is invalidated, React Query refetches fresh data in the background and updates the UI once the new data is available.
import { useMutation, useQueryClient } from "@tanstack/react-query";
const createUser = async (newUser) => {
const response = await fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(newUser),
});
if (!response.ok) {
throw new Error("Failed to create user");
}
return response.json();
};
function AddUser() {
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: createUser,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["users"] });
},
});
return (
<button onClick={() => mutation.mutate({ name: "John" })}>
Add User
</button>
);
}
Here, after successfully creating a user, the ["users"] query is invalidated. React Query then refetches the updated users list, ensuring the UI stays in sync with the backend without manual refetch logic.
React Query Devtools
The best thing about React Query is that it includes specialized devtools that let users examine their API calls. They can see what data is called with what payload, how long it is cached, and other details.
Installation of React query Devtools
npm install @tanstack/react-query-devtools
yarn add @tanstack/react-query-devtools
pnpm add @tanstack/react-query-devtools
After installation, just open your query provider and import React Query Devtools and simply call that inside QueryClientProvider.
Example
// src/providers/query-provider.jsx
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
const queryClient = new QueryClient();
const QueryProvider = ({ children }) => {
return (
<QueryClientProvider client={queryClient}>
{children}
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
);
};
export default QueryProvider;
Now you will see an icon on the bottom right side by clicking on that, you will get your devtools.
By clicking on this icon, you'll get a panel.
When Should You Use React Query?
React Query is well suited for applications that rely heavily on server-side data and frequent API interactions. If your app fetches, updates, or synchronizes data with a backend, React Query can significantly simplify your workflow.
Use React Query when:
- Your app makes frequent API calls (dashboards, admin panels, analytics apps)
- Data needs to stay in sync with the server
- You want automatic caching to avoid unnecessary requests
- Your UI depends on real-time or frequently changing data
- You’re tired of manually handling loading, error, and refetch logic
- You need features like pagination, infinite scroll, or background updates
You might not need React Query when:
- Your app is mostly static with minimal data fetching
- Data is purely client-side state (form inputs, modal state, UI toggles)
- You only make one or two simple API calls and want minimal setup
Conclusion
With caching and invalidation handled automatically, React Query removes the need to manually track API calls, loading states, and data freshness. This makes applications more performant, predictable, and easier to maintain—especially at scale.
FAQs
- What is stale in react query
Stale is a property in react query which helps to define how long data will be cached, by default stale time is 0 in tanstack react query. It take time is milisecond. - What is gctime in react query
GcTime is also known as Garbage collector time, The default time is 5 min, that means when data is inactive, Meaning You fetch some data on a page then you leave that, navigate to another page, that data will go under Inactive after 5 min react query kill and if you again come same page react query fetch fresh data again. you can edit this value inuseQueryhook.
References
- React Query Official Documentation
https://tanstack.com/query/latest - React Query Guide—Refine
https://refine.dev/blog/react-query-guide