Redux is great for client state (is the modal open?), but terrible for server state (is this data fresh?). React Query (now TanStack Query) manages caching, background updates, and stale data automaticallly.
The Default Stale-While-Revalidate Strategy
React Query assumes data is stale immediately (0ms) but keeps it in cache for 5 minutes. When you request data, it shows the cached version (fast!) while fetching the new version in the background.
import { useQuery } from 'react-query'
function Todos() {
const { isLoading, error, data } = useQuery('todos', fetchTodos)
if (isLoading) return 'Loading...'
return (
<ul>
{data.map(todo => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
)
}
DevTools
Always install the React Query DevTools to visualize the state of your queries (Fresh, Fetching, Stale, Inactive).
Key Takeaways
- Stop putting API data in Redux/Context.
- Use **Query Keys** effectively (e.g., `[‘todos’, { status: ‘done’ }]`) to segment cache.
- Automatic retries on network failure make apps resilient.
Discover more from C4: Container, Code, Cloud & Context
Subscribe to get the latest posts sent to your email.