Back to results for “Performance (memo/useMemo)”
React › Data Fetching (React Query & SWR)

How does automatic caching work in React Query, and why does it make an app feel faster?

Intermediate

Answer

React Query stores the result of each request under a unique key, and if a component asks for that same key again, it shows the cached data instantly while quietly checking in the background whether the data has changed on the server. This means users often see content immediately instead of waiting for a fresh network request every time.
// Both components share the same cached result automatically
useQuery({ queryKey: ['user', 5], queryFn: () => fetchUser(5) });

// Later, on a different page
useQuery({ queryKey: ['user', 5], queryFn: () => fetchUser(5) }); // instantly returns cached data first
Real-world example A social media app shows a user's profile instantly when navigating back to a previously viewed page, since React Query already had that exact profile data cached from the first visit only moments earlier.

Common follow-ups: How long does React Query keep cached data before considering it too old by default?;How would you manually clear or update a specific piece of cached data?