Why Tanstack Query ?
7 min read249 views
- #api
- #tanstack-query
- #react
Fetching data in React used to mean useEffect, loading states, race conditions, callback hells and a lot of boilerplate. TanStack Query solves this by handling server state for you - caching, refetching, synchronization, and more, with almost zero configuration. Let's see how it's approach makes that process easier.

But first what is TanStack Query ?#
TanStack Query (formerly React Query) is a data-fetching and caching library for Front-End apps, mainly used with React, but it also supports Vue, Svelte, and more. Mainly managing server state (ex. data that is coming from an API call) without writing a ton of boilerplate.
What it solves ?#
Fetching data in React used to mean useEffect, loading states, race conditions, and a lot of boilerplate. TanStack Query solves this by handling server state for you - caching, refetching, synchronization, and more - with almost zero configuration.
TanStack Query is great for#
- Server state management: Unlike global state managers like Zustand Or Redux, which focus on client state, TanStack Query is specifically designed for server state. This eliminates the need to manually caching, synchronize, or handle errors.
- Caching: Queries are cached by default, so subsequent requests fetch from cache instead of hitting the API unnecessarily and only updates the data when necessary resulting in a better performance
- Data refetching: With features like data refetching and background synchronization, TanStack Query ensures that data stays up-to-date. For instance, when a user navigates back to a page or refocuses a browser tab, TanStack Query automatically refreshes the data.
- Error Handling: Errors are handled centrally, reducing the need for boilerplate code.
- Query Invalidation: Invalidate and refetch queries with a single call (queryClient.invalidateQueries).
- On-Success and On-Error Callbacks: Define actions to take when a mutation succeeds or fails.
TanStack Query vs. old traditional approach#
Let's say you have function that retrieves user's data something like this
// @/src/api/user-api.js
import axios from "axios";
import {getUserData} form "@/src/api/user-api.js";
export async function getUserData() {
const res = await axios.get("/user-data");
return res.data;
}
Now comes the part when u want to use it in your application
- the traditional way (useState && useEffect) In order to do that you may have to do something like
// @/src/components/user-profile.jsx
import { useState, useEffect } from "react";
import { getUserData } from "@/src/api/user-api";
export default function UserProfile() {
const [userData, setUserData] = useState([]);
useEffect(() => {
async function fetchUserData() {
const data = await getUserData();
setUserData(data);
}
});
return <div>{/* display data */}</div>;
}
Now what about displaying loading indicators ?#
// @/src/components/user-profile.jsx
import { useState, useEffect } from "react";
import { getUserData } from "@/src/api/user-api";
export default function UserProfile() {
const [userData, setUserData] = useState([]);
// loading state
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
async function fetchUserData() {
setLoading(true);
const data = await getUserData();
setUserData(data);
setIsLoading(false);
}
});
if (isLoading) return <p>Loading....</p>;
return (
<section>
<div>{/* display data */}</div>
</section>
);
}
And of course you want to display errors, don't you ?#
so you might do something like this ?
// @/src/components/user-profile.jsx
import { useState, useEffect } from "react";
import { getUserData } from "@/src/api/user-api";
export default function UserProfile() {
const [userData, setUserData] = useState([]);
// loading state
const [isLoading, setIsLoading] = useState(false);
// error state
const [error, setError] = useState(null);
useEffect(() => {
async function fetchUserData() {
setLoading(true);
try {
const data = await getUserData();
setUserData(data);
} catch (error) {
setError(error.message);
}
setIsLoading(false);
}
});
if (isLoading) return <p>Loading....</p>;
if (error) return <p>{error.maessage}</p>;
return (
<section>
<div>{/* display data */}</div>
</section>
);
}
What if you have multiple API calls and worse, you have multiple mutations#
you will start to see your code becomes bloated so fast and a debugging nightmare
Now considering Tanstack Query might become convenient#
there's some ways you can use it but the way i prefer is custom hooks
so i do something like this
// @/src/api/use-user-data.ts
import { useQuery } from "@tanstack/react-query";
export const useUserData = () => {
return useQuery({
queryKey: ["user_data"],
queryFn: getUserData
});
};
Now using it in your component
// @/src/components/user-profile.jsx
import { useUserData } from "@/src/api/use-user-data";
export default function UserProfile() {
const { data: userData, isLoading, error } = useUserData();
if (isLoading) return <p>Loading....</p>;
if (error) return <p>{error.maessage}</p>;
return (
<section>
<div>{/* display data */}</div>
</section>
);
}
Now you will start to see the difference it already provides you with built in loading and errors state and much more built in returns.
no useEffect, no useState, no headache
You have more api calls to do?#
it's as simple as adding a new hook and using it
// @/src/api/use-update-user.ts
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
const queryClient = useQueryClient();
export const useUpdateUser = () => {
return useMutation({
mutationFn: (updatedUser) => updateUserName(updatedUser),
onSuccess: () => {
toast.success("User updated succesfully");
/* in Tanstack Query it provides the ability to assign keys to your data
so later you can use that key to easily revalidate your data or delete them
so in our example you will do something like this.
*/
queryClient.invalidateQueries(["user_data"]);
},
onError: (error) => {
console.error(error);
toast.error("Unable to update user data!");
}
});
};
Now to use it in your component
// @/src/components/user-profile.jsx
import { useUserData } from "@/src/api/use-user-data";
import { useUpdateUser } from "@/src/api/use-update-user";
export default function UserProfile() {
const { data: userData, isLoading: isLoadingUser, error } = useUserData();
const { mutate: updateUser, isPending: isUpdatingUser } = useUpdateUser();
const isLoading = isLoadingUser || isUpdatingUser;
if (isLoading) return <p>Loading....</p>;
if (error) return <p>{error.maessage}</p>;
return (
<section>
<div>{/* display data */}</div>
<UpdateUserForm onSubmit={updateUser} />
</section>
);
}
What you gained doing all that#
- Caching: Queries are cached by default, so subsequent requests fetch from cache instead of hitting the API unnecessarily.
- Auto Refetch: Stale queries are automatically refetched when the component mounts.
- Retries: Failed requests are retried automatically based on a configurable retry policy.
- Error Handling: Errors are handled centrally, reducing the need for boilerplate code.
- Query Invalidation: Invalidate and refetch queries with a single call (queryClient.invalidateQueries) or using the refetch method that it provides.
- On-Success and On-Error Callbacks: Define actions to take when a mutation succeeds or fails.
How to set up TanstackQuery#
Installation
npm i @tanstack/react-query
Setting Up QueryClient
// main.jsx
import React from "react";
import ReactDOM from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import App from "./App";
const queryClient = new QueryClient();
ReactDOM.createRoot(document.getElementById("root")).render(
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
);
and that's it you now can start using Tanstack Query.
Additionally you can use their dev-tools which is a game changer for your debugging process
npm install @tanstack/react-query-devtools
now add it to your app
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
function App() {
return (
<>
{/* Your application components */}
<ReactQueryDevtools initialIsOpen={false} />
</>
);
}
through the devtools you can do stuff like trigger loading state, errors, revalidating....
In conclusion#
TanStack Query is a powerful tool for managing server state, simplifying asynchronous data handling, and enhancing application performance. Its extensive features, like smart caching, refetching, and seamless TypeScript support, making it an excellent choice for modern applications.
it offers a significant advantages in managing data fetching and caching for web applications. It provides features like automatic caching, refetching, and retrying, which are among its most commonly used functionalities. Additionally, it includes a wide range of built-in features that can effectively address complex challenges related to API calls.