TanStack Query
TanStack Query (formerly React Query) is a data-fetching and caching library that manages server state in frontend applications, handling caching, background refetching, and synchronization automatically.
Definition
TanStack Query (formerly React Query) is a data-fetching and caching library that manages server state in frontend applications, handling caching, background refetching, and synchronization automatically.
Overview
Most client-side state libraries like Redux or Zustand are designed for state that lives entirely on the client. TanStack Query addresses a different problem: 'server state' — data that originates from a remote source, can become stale, and may be updated by other users or processes outside the application's control. It wraps data-fetching calls (to a REST API or GraphQL endpoint) in a caching layer that tracks loading, error, and success states automatically. A typical usage pattern uses the useQuery hook to fetch and cache data keyed by a query key, and useMutation to perform writes, with built-in support for automatic background refetching (e.g. when the window regains focus or network reconnects), stale-while-revalidate caching so users see cached data instantly while fresh data loads in the background, retries with backoff on failure, and optimistic updates that update the UI immediately before a mutation confirms. Originally built for React and known as React Query, the library was rebranded to TanStack Query as adapters for Vue, Svelte, Solid, and Angular were added, reflecting a broader shift toward framework-agnostic core logic with thin framework-specific bindings. It's commonly paired with a lightweight client-state library — Zustand or Recoil in React apps, Pinia in Vue apps — since TanStack Query intentionally doesn't manage pure UI state, only server-derived data. SWR is the most direct alternative, offering a similar stale-while-revalidate model with a smaller feature set.
Key Features
- Automatic caching of server data keyed by a query key
- Background refetching on window focus, network reconnect, or interval
- Stale-while-revalidate strategy shows cached data instantly while refreshing
- Built-in loading, error, and success state tracking for queries
- Optimistic updates for mutations before server confirmation
- Automatic retries with configurable backoff on failed requests
- Framework adapters for React, Vue, Svelte, Solid, and Angular