Caching in React: A Complete Guide to Building Faster Web Applications
Imagine opening an e-commerce website, browsing products, visiting a product details page, and returning to the product listing.
Should the application fetch the same products again?
Not necessarily.
A well-designed web application can reuse previously fetched data, reduce unnecessary network requests, and deliver a faster user experience. This is where caching comes in.
In this article, we’ll explore how caching works in React applications, the different caching layers, practical implementations, and how to choose the right strategy for production applications.
1. What Is Caching?
Caching is the process of storing previously retrieved or computed data so it can be reused instead of performing the same operation repeatedly.
For example, suppose a React application fetches products from an API.
const response = await fetch("/api/products");
const products = await response.json();Every time this request runs, the browser might need to communicate with the server.
If the data is already available and hasn’t changed, we may be able to reuse a cached response instead.
Caching can improve:
- Page load performance
- API response times
- Network efficiency
- Backend scalability
- User experience on slow networks
However, caching introduces another important question:
How do we know whether cached data is still valid?
The answer depends on the caching strategy, expiration rules, and whether the data can change.
2. Understanding the Different Caching Layers
Caching in a React application isn’t limited to React itself. It can happen at multiple layers.
A. In-memory caching
In-memory caching stores data in JavaScript memory while the application is running.
For example:
const cache = new Map();
async function getProducts() {
if (cache.has("products")) {
return cache.get("products");
}
const response = await fetch("/api/products");
const products = await response.json();
cache.set("products", products);
return products;
}
The first call fetches products from the API. Subsequent calls reuse the stored result.
Advantages:
- Fast access
- No additional network request when cached data is reused
- Simple implementation for basic use cases
Limitations:
- Data disappears when the page is fully reloaded.
- Cache invalidation must be handled.
- Concurrent requests can still duplicate network calls.
- A plain Map doesn't automatically manage expiration or stale data.
For production applications, libraries such as TanStack Query or SWR generally provide a more complete solution.
B. Browser HTTP caching
Browsers can cache HTTP responses based on headers returned by the server.
Common examples include:
- JavaScript bundles
- CSS files
- Images
- Fonts
- Some API responses
For example, a server might return:
Cache-Control: public, max-age=31536000, immutable
This tells compliant caches that the resource can be considered fresh for one year.
This policy is appropriate for versioned static assets, such as JavaScript files containing content hashes in their filenames.
C. Persistent browser storage
Sometimes data must survive a page reload.
Two common options are localStorage and IndexedDB.
localStorage is useful for small pieces of persistent data, such as UI preferences.
localStorage.setItem("theme", "dark");const theme = localStorage.getItem("theme");IndexedDB is more suitable for larger structured datasets and offline application data.
Neither storage mechanism automatically synchronizes with your backend or guarantees that stored data remains current.
D. Service worker caching
A service worker can intercept network requests and respond using cached resources.
This is useful for Progressive Web Apps (PWAs) that need offline functionality or controlled network strategies.
A service worker can implement strategies such as cache first, network first, and stale while revalidate.
3. Caching API Responses with TanStack Query
For many React applications, caching server data is one of the most important performance improvements.
Consider an application that displays products, categories, and search results.
Without a caching library, developers often need to manage loading states, API errors, duplicate requests, data expiration, refetching, and cache invalidation manually.
TanStack Query, previously known as React Query, handles much of this complexity.
Step 1: Install TanStack Query
npm install @tanstack/react-query
Step 2: Configure the QueryClient
import {
QueryClient,
QueryClientProvider,
} from "@tanstack/react-query";import Products from "./Products";
const queryClient = new QueryClient();
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<Products />
</QueryClientProvider>
);
}The QueryClient manages the query cache and related behavior.
Create it outside the component so it isn’t recreated on every render.
Step 3: Fetch and cache products
import { useQuery } from "@tanstack/react-query";async function fetchProducts() {
const response = await fetch("/api/products"); if (!response.ok) {
throw new Error("Failed to fetch products");
}return response.json();
}
export default function Products() {
const {
data,
isLoading,
error,
} = useQuery({
queryKey: ["products"],
queryFn: fetchProducts,
staleTime: 60 * 1000,
});if (isLoading) return <p>Loading products...</p>;
if (error) return <p>Something went wrong.</p>;
return (
<div>
{data.map((product) => (
<div key={product.id}>
<h3>{product.name}</h3>
<p>₹{product.price}</p>
</div>
))}
</div>
);
}
Let’s understand the important configuration.
queryKey
queryKey: ["products"]
This uniquely identifies the query in the cache.
When another component uses the same query key and compatible query configuration, it can reuse the cached data.
If the query depends on search terms, filters, or pagination, include them in the key:
queryKey: [
"products",
{ category: "electronics", page: 1 }
]
Different categories and pages then have separate cache entries.
queryFn
queryFn: fetchProducts
This function retrieves the data. TanStack Query executes it when a fetch is required.
staleTime
staleTime: 60 * 1000
The cached data is considered fresh for 60 seconds after it is successfully fetched.
During this period, another observer using the same query can reuse the fresh data without an automatic refetch caused by mounting.
Once the data becomes stale, it may be refetched when a configured trigger occurs, such as a component mounting or the window regaining focus.
gcTime
gcTime controls how long an inactive query remains in the cache before garbage collection.
useQuery({
queryKey: ["products"],
queryFn: fetchProducts,
staleTime: 60 * 1000,
gcTime: 5 * 60 * 1000,
});The data can be fresh for one minute, while an inactive cache entry can remain available for up to five minutes before being garbage-collected, assuming it stays inactive.
Freshness and retention are two different concepts.
4. Understanding staleTime vs gcTime
This is a common React interview question.
Think of them as answering two different questions.
staleTime: How long can I treat this data as fresh?
gcTime: How long should I retain this inactive data?
Consider the following timeline:
- At 10:00, the application fetches products.
- Until 10:01, the data is fresh.
- At 10:02, the data is stale, but it can still be displayed.
- If the query becomes inactive, its cache entry may remain available for another five minutes, depending on the configured gcTime.
- If the query is used again while the cached data remains, the application may display that data and refetch it if appropriate.
Being stale does not mean being deleted. It means the data is eligible for revalidation.
5. HTTP Caching with Cache-Control
TanStack Query manages application-level server state. HTTP caching is a separate layer.
Suppose your application serves these resources:
/index.html
/assets/app-a81f2c.js
/assets/styles-b17e93.css
/api/products
/api/products/123
These resources should not necessarily have the same caching policy.
Long-term caching for static assets
For content-hashed assets:
Cache-Control: public, max-age=31536000, immutable
A new build produces new asset filenames when their content changes.
This allows the browser and CDN to cache old assets for a long time without confusing them with the new version.
Revalidation for HTML
For the HTML entry point:
Cache-Control: no-cache
This allows the response to be stored but requires revalidation before reuse.
That helps the browser discover a new deployment rather than indefinitely reusing an outdated HTML document.
Caching API responses
For suitable non-sensitive API responses:
Cache-Control: private, max-age=60
The browser can cache the response privately for 60 seconds.
For data that must not be stored by HTTP caches:
Cache-Control: no-store
The correct policy depends on the data, authentication model, and product requirements.
6. How ETag Reduces Network Transfer
Imagine a browser has already downloaded a product listing.
Instead of downloading the entire response again, the browser can revalidate its cached copy using an ETag.
The server might initially return:
HTTP/1.1 200 OK
ETag: "products-v1"
Cache-Control: no-cache
Content-Type: application/json
The browser stores the response and its validator.
On a later request, it sends:
If-None-Match: "products-v1"
If the resource hasn’t changed, the server responds:
HTTP/1.1 304 Not Modified
ETag: "products-v1"
The browser can reuse its stored response body.
If the resource has changed, the server returns a fresh response, usually with status 200 OK and a new validator.
Important: A 304 Not Modified response saves transferring the full response body, but it still requires a network round trip. A fresh cached response can sometimes be served without contacting the server at all.
7. Implementing a Simple Cache with Expiration
If you want to understand the underlying concept before using a library, here’s a simple in-memory cache.
const cache = new Map();
async function cachedFetch(key, url, ttl = 60_000) {
const cached = cache.get(key); if (cached && Date.now() < cached.expiresAt) {
return cached.data;
}const response = await fetch(url);
if (!response.ok) {
throw new Error("Request failed");
}const data = await response.json();
cache.set(key, {
data,
expiresAt: Date.now() + ttl,
});return data;
}
Usage:
const products = await cachedFetch(
"products",
"/api/products",
60_000
);
This implementation returns cached data while its time-to-live (TTL) hasn’t expired.
However, it is intentionally simple. A production implementation may need request deduplication, cache invalidation, memory limits, error handling, and handling of concurrent requests.
For a React application with many server-state queries, a dedicated library is generally preferable.
8. What Happens When Data Changes?
Imagine a user adds a product to their wishlist.
The cache might still contain the previous wishlist. If the application continues to display it, the UI becomes inconsistent.
One solution is to invalidate the relevant query after a successful mutation.
import {
useMutation,
useQueryClient,
} from "@tanstack/react-query";function AddToWishlist() {
const queryClient = useQueryClient(); const mutation = useMutation({
mutationFn: async (productId) => {
const response = await fetch("/api/wishlist", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ productId }),
}); if (!response.ok) {
throw new Error("Failed to update wishlist");
}return response.json();
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ["wishlist"],
});
},
});return (
<button
onClick={() => mutation.mutate("product-123")}
>
Add to wishlist
</button>
);
}
After the mutation succeeds, matching wishlist queries become stale and can refetch when appropriate.
Another approach is to update cached data directly with setQueryData. This can make the interface feel faster, but the cache must be updated correctly.
Optimistic updates can temporarily update the UI before the server confirms the change, with rollback if the request fails.
9. Service Workers and Offline Caching
If your application needs to work offline, ordinary API caching alone might not be sufficient.
A service worker can intercept network requests and decide how to respond.
Three common strategies are:
Cache first
Check the cache before going to the network.
Best for stable assets such as logos, fonts, and versioned images.
Network first
Try the network first, then fall back to cached content when appropriate.
Useful for data where freshness is important but offline fallback is valuable.
Stale while revalidate
Return cached content immediately, while fetching an updated version in the background.
Useful for content where showing something quickly matters more than displaying the newest version immediately.
Libraries such as Workbox help implement these strategies.
Be careful when caching authenticated API responses. An incorrect cache policy can expose one user’s data to another user on a shared device or retain information after logout.
A service worker does not automatically make every API request available offline. You must deliberately configure the resources and fallback behavior.
10. Common Caching Mistakes
Mistake 1: Assuming stale data is deleted
Stale data can still be present in the cache and may be displayed while a refetch happens.
Mistake 2: Using the same query key for different data
Products for different pages, categories, or search terms should have appropriate query keys.
Mistake 3: Caching everything for too long
Frequently changing data may require shorter freshness windows or more active invalidation.
Mistake 4: Ignoring mutations
After an update, create, or delete operation, the relevant cache entries may need to be updated or invalidated.
Mistake 5: Confusing React Query with browser caching
React Query manages server state inside the application. HTTP caching operates through browser and intermediary cache rules. Both can work together.
Mistake 6: Caching sensitive information carelessly
Avoid broad public caching policies for authenticated or user-specific responses. Choose cache keys and storage rules that respect user boundaries, and clear or invalidate sensitive application state when appropriate.
11. How I Would Design Caching for a Production React Application
For a typical production application, I would use multiple layers:
- Static assets: Content-hashed JavaScript, CSS, and image files cached through a CDN and browser HTTP caching.
- HTML: Revalidation so new deployments are discovered.
- API data: TanStack Query or SWR, with query keys, freshness settings, and mutation-driven invalidation.
- Persistent data: IndexedDB only when offline access or persistence is required.
- Offline support: A service worker with carefully selected caching strategies.
- Security: Appropriate HTTP headers and isolation of user-specific cached data.
I would then measure API latency, cache hit rates, repeated requests, memory usage, and the frequency of stale-data problems.
Caching is not simply about maximizing cache hits. It is about finding the right balance between performance, freshness, memory usage, and correctness.
12. Interview Quick Revision
What is caching?
Storing and reusing previously retrieved or computed data to avoid unnecessary work.
What is the difference between staleTime and gcTime?
staleTime controls freshness; gcTime controls how long inactive queries remain cached.
What is the difference between no-cache and no-store?
no-cache allows storage but requires revalidation before reuse. no-store tells compliant caches not to store the response.
Does React Query persist data after a refresh?
Not by default. Its normal cache is in memory, although persistence can be configured.
How do you invalidate cached API data after an update?
Use query invalidation or update the cached data directly.
How would you cache static assets?
Use content-hashed filenames, appropriate HTTP cache headers, and a CDN.
How would you support offline functionality?
Use a service worker and, when necessary, persistent storage such as IndexedDB.
Final Thoughts
Caching is one of the most effective ways to improve web application performance, but different problems require different solutions.
Use TanStack Query for server-state management, HTTP caching for network resources, IndexedDB for persistent structured data, and service workers when offline behavior is required.
The key principle is simple:
Cache data when reuse is safe, define how it becomes stale, and make sure updates invalidate or refresh the right information.