useQuery useQuery Data Fetching
Last updated: 2026-11-02
useQuery useQuery Data Fetching
useQuery from TanStack Query manages the whole request lifecycle plus the cache: it deduplicates automatically, refetches in the background, staleTime controls how long the data stays fresh, and invalidateQueries marks entries as stale so they refetch. The component only declares which data it needs and leaves the rest to the library, so the same query is never fetched twice for two components.
| Group | Data & Engineering |
|---|---|
| Kind | Hook |
| Since | TanStack Query v5 |
ℹ️ Info The editor transpiles JSX to JavaScript and renders the real UI in a sandbox; components mount automatically — no manual render call needed.
📝 Syntax
import { useQuery } from '@tanstack/react-query'
const { data, isPending, isError, error, refetch } = useQuery({
queryKey: ['todo', id], // cache key: a change switches to or refetches the query
queryFn: () => fetch('/api/todos/' + id).then(r => r.json()),
staleTime: 30_000 // fresh for 30 seconds, no refetch needed
})
// isPending: first load without a cache; isFetching: any background refetch
⚙️ Parameters
| queryKey | The cache key (an array): in ['todos', id] a changed id switches to the matching cache entry and refetches, while an identical key reuses the cache. |
|---|---|
| staleTime | How long the data stays fresh (milliseconds): within that window a remount uses the cache directly, afterwards a remount refreshes silently in the background (stale-while-revalidate). |
Returns:Returns the query state such as { data, isPending, isError, error, refetch, isFetching }: data holds the latest data and refetch invalidates the entry and fetches it again manually.
▶ Example
The example runs out of the box: it auto-renders when expanded, and edits take effect instantly.
Output:
The first read waits 0.8 seconds; afterwards "Read" returns instantly because the Map cache hits, and "refetch" forces a new request and refreshes the cache - the core ideas behind staleTime and invalidation (simulated demo).