Capítulo 1 de 80

Chapter 1: Overview

Core Idea

TanStack Query (formerly React Query) is a server-state library: it fetches, caches, synchronizes and updates data that lives on a server, which behaves fundamentally differently from client state (it's owned elsewhere, can go stale, and must be fetched/updated asynchronously).

Key Concepts

  • Server state vs. client state: server state is persisted remotely, fetched/updated async, shared with others, and can silently go stale — traditional state managers (Redux-style) are built for client state and don't model this well.
  • What the library actually solves: caching, deduping identical in-flight requests, background refetching of stale data, pagination/lazy-loading, structural-sharing memoization of results, garbage collection of unused cache entries.
  • Core primitives (detailed in later chapters): QueryClient + QueryClientProvider own the cache; useQuery reads/subscribes to a cache entry keyed by a queryKey; useMutation performs writes.

Code Examples

import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query'

const queryClient = new QueryClient()

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <Example />
    </QueryClientProvider>
  )
}

function Example() {
  const { isPending, error, data } = useQuery({
    queryKey: ['repoData'],
    queryFn: () => fetch('https://api.github.com/repos/TanStack/query').then((res) => res.json()),
  })

  if (isPending) return 'Loading...'
  if (error) return 'An error has occurred: ' + error.message
  return <div>{data.name}</div>
}
  • What it demonstrates: the minimal shape of every TanStack Query app — one QueryClient at the root, one useQuery call per piece of server data, and the isPending/error/data triad every query result exposes.

Key Takeaways

  1. Reach for TanStack Query specifically for server state — it is not a general client-state replacement for useState/Redux/Zustand.
  2. The three recurring challenges it exists to solve are caching, background freshness, and dedup/GC of requests — keep these in mind when a feature seems "extra," it's usually solving one of them.
  3. isPending/error/data is the baseline shape of a query result; later chapters cover the fuller status model.

Connects To

  • Installation: next step after understanding the motivation.
  • Queries: deep dive on useQuery and the cache-key model introduced here.
  • Comparison: how this positioning differs from SWR/Apollo/RTK Query/React Router.