React Query: Server State vs Client State

On this page

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.

JavaScript15 lines
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.

Written by

Nithin Mohan TK

Hello Namaste! 👋🏻 I'm an accomplished Enterprise Solution Architect & Engineering Leader with 20+ years of progressive experience architecting, building, and scaling transformative enterprise solutions. ⚜️ Solution Architect / AI & Cloud 📌 Galway, Ireland

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.