React web apps often need to fetch data from external APIs and display it. That means deciding how to fetch it, what to show while a request is loading or after it fails, and how to cache the response so you don't keep making the same request.
TanStack Query
helps with those tasks. Originally known as
React Query
, it has grown into a server-state library for multiple frameworks. We'll use React and work through examples from basic queries to more advanced caching patterns.
TanStack Query helps client applications manage server state. It handles data returned by a server and simplifies loading states, errors, caching, and refetching.
For example, you can use it to:
Fetch posts from an API and show them on screen.
Cache the response to avoid repeating the same request.
Show a loading spinner while the request is pending.
First, define an asynchronous function that fetches and returns the data.
Pass it to the queryFn option in useQuery.
The useQuery hook calls the function and caches its result.
React's Suspense and TanStack Query can work together to make loading states more declarative. Wrap the querying component in a Suspense boundary. The example uses the older useQuery option suspense: true. Check the API for your installed version before using it.
Use them to inspect cached data, query status, and request timing when debugging.
Use TanStack Query with Server-Side Rendering ๐
In a framework like Next.js, you can prefetch queries on the server and include their data in the initial page payload to speed up initial rendering.
This example uses dehydrate and the older Hydrate component.
TanStack Query is a flexible tool for working with asynchronous data in React. Beyond basic useQuery and useMutation usage, it supports caching, invalidation, conditional queries, infinite scrolling, Suspense, and server-side rendering. These features simplify logic that would otherwise be complex to implement yourself.
Try applying the examples and strategies from this guide in a project.