React Query is a powerful library for managing server state in React applications. One of its standout features is its intelligent caching mechanism, which can significantly improve application performance and user experience. Two essential concepts in this mechanism are staleTime and cacheTime.
In this blog, we’ll break down how caching works in React Query and clarify the roles of staleTime and cacheTime in managing data freshness and memory optimization.
React Query caches the results of asynchronous data-fetching functions (like API calls). This allows it to serve data instantly from memory on future requests, avoiding unnecessary network calls and improving speed.
However, not all cached data remains valid indefinitely. That’s where staleTime and cacheTime come in.
staleTime defines how long the data fetched by a query is considered fresh. During this period, React Query will not refetch the data when the component mounts or regains focus. It assumes the data is still valid.
Example:
useQuery(['user', userId], fetchUser, {
staleTime: 5 * 60 * 1000, // 5 minutes
});
In the above case, React Query treats the fetched user data as fresh for 5 minutes. No background refetch will occur when the user revisits the component within that time.
Use Case: Use staleTime when the data doesn’t change frequently, such as product listings or user profiles.
cacheTime defines how long the cached data remains in memory after it becomes unused (i.e., no component is using it). If no component requires the data and the cacheTime expires, React Query will garbage-collect the data.
Example:
useQuery(['user', userId], fetchUser, {
cacheTime: 10 * 60 * 1000, // 10 minutes
});
In this case, if no component uses the query for 10 minutes, the cached data will be removed.
Use Case: Use a longer cacheTime when you want to preserve data in memory across navigation or component unmounting.
| Property | Purpose | Default |
| staleTime | Controls when data becomes stale | 0 (immediate) |
| cacheTime | How long unused data stays in memory | 5 minutes |
React Query uses query keys to uniquely identify cached data. A good practice is to use an array structure for query keys to ensure clear, distinct cache entries.
useQuery(['user', userId], fetchUser);
Each unique key ([‘user’, userId]) allows React Query to manage cache separately, preventing collisions and enabling accurate data retrieval.
React Query enables background refetching for stale data. Even if the data is available from the cache, React Query can silently update it in the background under certain conditions:
useQuery(['posts'], fetchPosts, {
refetchOnWindowFocus: true,
refetchOnReconnect: true,
});
This ensures users always see the most recent data without noticeable loading states.
React Query provides programmatic methods to manage the cache using the queryClient instance:
Invalidate cached data:
queryClient.invalidateQueries(['user', userId]);
Update cached data manually:
queryClient.setQueryData(['user', userId], updatedUserData);
Remove cache entries:
queryClient.removeQueries(['user', userId]);
These methods offer fine-grained control over the cache, especially useful after mutations or external updates.
By understanding and tuning these caching strategies, you can make your React Query implementation more efficient, consistent, and optimized for real-world applications.
Work with our skilled React developers to accelerate your project and boost its performance.
Hire Reactjs Developers