Repeated API requests are a common challenge in React applications. A product listing, dashboard or analytics page may fetch the same information multiple times as users navigate between screens.
React API caching with TanStack Query provides a structured approach to managing server state, reusing responses and keeping application data up to date.
This guide uses TanStack Query v5.
1. Why React applications make repeated API calls
A typical React component fetches data inside useEffect:
useEffect(() => {
fetch("/api/products")
.then(response => {
if (!response.ok) {
throw new Error("Request failed");
}
return response.json();
})
.then(setProducts)
.catch(setError);
}, []);The empty dependency array prevents this effect from running on every ordinary re-render. However, when the component unmounts and mounts again, the effect runs again.
Multiple components may also independently fetch the same endpoint.
Although useEffect is useful for synchronizing with external systems, implementing shared caching, cancellation, retries and request coordination manually can become difficult.
2. What is TanStack Query?
TanStack Query is a server-state management library that provides tools for fetching, caching, synchronizing and updating asynchronous data.
Its capabilities include shared query caching, background refetching, loading and error states, mutations and query invalidation.
Unlike local UI state, server state can change outside your application. A caching strategy must therefore balance request efficiency with data freshness.
3. Installing TanStack Query
Install the React package:
npm install @tanstack/react-queryConfigure a QueryClient at the application root:
import {
QueryClient,
QueryClientProvider
} from "@tanstack/react-query";
const queryClient = new QueryClient();
export default function Root() {
return (
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
);
}For a typical client-side React application, keep the QueryClient stable instead of creating a new instance on every render.
Server-rendered applications require additional care to isolate request-specific caches.
4. Implement React API caching using useQuery
Create a reusable fetching function:
async function fetchProducts({ signal }) {
const response = await fetch("/api/products", {
signal
});
if (!response.ok) {
throw new Error("Unable to fetch products");
}
return response.json();
}Use it inside your component:
import { useQuery } from "@tanstack/react-query";
function Products() {
const { data, isPending, isError } = useQuery({
queryKey: ["products"],
queryFn: fetchProducts,
staleTime: 60_000,
gcTime: 300_000
});
if (isPending) return <p>Loading...</p>;
if (isError) return <p>Unable to load products.</p>;
return data.map(product => (
<div key={product.id}>{product.name}</div>
));
}Components using the same query key and QueryClient can share cached data. Concurrent requests for the same query can also share an in-flight fetch.
This example assumes the API returns an array of products.
5. Understanding staleTime vs gcTime
staleTime
staleTime controls how long successfully fetched data is considered fresh.
For example, staleTime: 60_000 means the data is considered fresh for one minute. During that period, an ordinary component remount does not normally trigger a refetch.
Once data becomes stale, eligible events such as mounting, reconnecting or window focus may trigger a background refetch.
Becoming stale does not itself automatically initiate a request.
gcTime
gcTime controls how long an inactive query remains in memory before garbage collection.
For example, gcTime: 300_000 keeps an inactive query cached for five minutes.
An active query is not removed simply because this duration has elapsed.
The two options solve different problems: staleTime controls freshness, while gcTime controls inactive cache retention.
6. Design query keys correctly
Query keys must include the variables that affect the returned data.
For a filtered product listing:
useQuery({
queryKey: ["products", { category, page }],
queryFn: () => fetchFilteredProducts(category, page)
});This separates different categories and pages into distinct cached queries.
Avoid using the same key for unrelated API responses. Incorrect query keys can cause components to display unexpected cached data.
7. Refresh cached data after mutations
Caching should not prevent users from seeing updated information.
After creating a product, invalidate the relevant product queries:
import {
useMutation,
useQueryClient
} from "@tanstack/react-query";
function useCreateProduct() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async product => {
const response = await fetch("/api/products", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(product)
});
if (!response.ok) {
throw new Error("Unable to create product");
}
return response.json();
},
onSuccess: () => {
return queryClient.invalidateQueries({
queryKey: ["products"]
});
}
});
}Invalidation marks matching queries as stale and normally refetches active matching queries in the background.
This allows product listings to reflect server-side changes without manually coordinating every component.
8. Choose a caching strategy for your use case
Different applications have different freshness requirements.
A relatively stable product catalog may benefit from a longer staleTime. A live inventory dashboard may require frequent refreshes, polling or event-driven updates.
Financial transactions and other sensitive operations may require explicit server validation before completing an action.
Do not use one caching configuration for every API. Consider how often the underlying data changes and the consequences of displaying outdated information.
9. Verify improvements using browser developer tools
Open the Network panel in Chrome DevTools and filter requests by your API endpoint.
Navigate between screens that consume the same query. Compare request counts before and after introducing caching.
Repeat the experiment with different staleTime values and verify that mutations refresh the correct queries.
Test loading, error and background fetching states. Also check that switching accounts or tenants does not expose another user’s cached data.
These observations are more useful than assuming caching always improves every performance metric.
10. Common mistakes to avoid
- Creating a new QueryClient on every render.
- Omitting filters or pagination variables from query keys.
- Using excessively long staleTime values for frequently changing data.
- Forgetting to invalidate relevant queries after mutations.
- Treating the query cache as a permanent database.
- Assuming every repeated request is unnecessary.
- Sharing sensitive cached data across authentication boundaries.
Frequently Asked Questions
Does TanStack Query replace Redux?
Not necessarily. TanStack Query specializes in server state. Redux can still be useful for complex client-side application state.
Does staleTime prevent every API request?
No. Manual refetching, invalidation and certain configurations can still initiate requests.
Is TanStack Query caching permanent?
No. The default query cache is in memory. Persistence requires additional configuration, and sensitive data needs appropriate handling.
Can TanStack Query work with GraphQL?
Yes. The query function can use a GraphQL client or any asynchronous request function. Query keys should include the variables that affect the result.
Does TanStack Query improve LCP?
It can help when unnecessary fetching delays visible content, but LCP also depends on server response time, rendering, resources and page architecture. Measure the actual impact.
Conclusion
React API caching with TanStack Query can simplify server-state management and reduce avoidable requests when configured correctly.
Start with stable query keys, appropriate freshness settings and targeted invalidation. Verify behavior using browser developer tools rather than relying on assumptions.
A well-designed caching strategy should improve the user experience without compromising data correctness.
Need assistance implementing API caching, debugging React applications or optimizing frontend performance? Tekody provides professional remote engineering and AI development support.
👉 Request Support: https://tekody.com/get-support/
📲 WhatsApp for Support: +91-8527854783