A Beginner’s Guide to TanStack Query with Examples

TanStack Query (formerly React Query) fetches, caches and updates server data in React apps. This beginner's tutorial covers v5: installation, useQuery, query keys, staleTime vs gcTime, mutations, pagination, DevTools and common mistakes.

A Beginner’s Guide to TanStack Query with Examples
AK
Ashish Kamat
Full-Stack Developer & Digital Marketer
July 16, 2025
4
2,725
#tanstack query#react query#react data fetching#tanstack react query tutorial#react query examples#tanstack query beginners guide#useQuery example#react query mutation#react query vs useEffect

TL;DR / Key Takeaway

  • TanStack Query (formerly React Query) fetches, caches and updates server data in React apps. This beginner's tutorial covers v5: installation, useQuery, query keys, staleTime vs gcTime, mutations, pagination, DevTools and common mistakes.

TanStack Query (formerly React Query) is a library that fetches, caches and updates server data in React apps, so you don't have to manage loading states, caching and refetching yourself with useState and useEffect. This tutorial covers TanStack Query v5, the current major version, from installation to mutations, caching and the mistakes beginners most often make.

What is TanStack Query?

TanStack Query manages server state: data that lives on a server and that your app only borrows, such as users, products or orders. It works with React, Vue, Solid, Svelte and Angular. It helps you:

  • Fetch, cache and update data with a few lines of code

  • Refetch automatically in the background so data stays fresh

  • Handle loading, error and success states consistently

  • Share the same cached data between components without prop drilling

Why use TanStack Query?

Without a data library, every component that fetches data ends up with the same boilerplate: a useEffect, a loading flag, an error flag, and no caching, so the same request runs again every time the component mounts. TanStack Query replaces that with a single hook and adds features that are hard to build by hand:

  • Caching: results are stored by key, so navigating back to a page shows data instantly

  • Background refetching: stale data is refreshed when the window regains focus or the network reconnects

  • Request deduplication: ten components asking for the same data trigger one request

  • Mutations: create, update and delete data, then refresh the affected queries

  • Pagination and infinite scrolling built in

  • DevTools for inspecting every query and its state

It doesn't replace client state such as whether a modal is open; keep that in useState or a small store like Zustand.

Installation

Install the package (TanStack Query v5 requires React 18 or newer):

npm install @tanstack/react-query

Create a QueryClient and wrap your app in a QueryClientProvider:

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

const queryClient = new QueryClient();

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

Using Next.js App Router? The provider must be a Client Component, and the client should be created inside it so every visitor gets their own cache:

// app/providers.tsx
'use client';

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

export function Providers({ children }: { children: React.ReactNode }) {
const [queryClient] = useState(() => new QueryClient());
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
}

Then wrap {children} in <Providers> inside app/layout.tsx.

Fetching data with useQuery

A query needs two things: a unique query key and a query function that returns a promise.

import { useQuery } from '@tanstack/react-query';

type User = { id: number; name: string };

async function fetchUsers(): Promise<User[]> {
const res = await fetch('https://jsonplaceholder.typicode.com/users');
if (!res.ok) throw new Error('Failed to fetch users');
return res.json();
}

function Users() {
const { data, isPending, isError, error } = useQuery({
queryKey: ['users'],
queryFn: fetchUsers,
});

if (isPending) return <p>Loading...</p>;
if (isError) return <p>Error: {error.message}</p>;

return (
<ul>
{data.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}

Two details matter here. First, fetch doesn't throw on HTTP errors, so check res.ok and throw yourself; otherwise TanStack Query treats a 500 response as success. Second, in v5 the first-load state is called isPending.

Query keys with parameters

The query key identifies cached data, so anything your query function depends on belongs in the key. When the key changes, TanStack Query fetches the new data automatically:

function UserDetails({ userId }: { userId: number }) {
const { data: user } = useQuery({
queryKey: ['users', userId],
queryFn: async () => {
const res = await fetch(`/api/users/${userId}`);
if (!res.ok) throw new Error('Failed to fetch user');
return res.json() as Promise<User>;
},
enabled: userId > 0, // don't run until we have a valid id
});

return <h2>{user?.name}</h2>;
}

The enabled option is how you write dependent queries: the query waits until a condition is true.

Caching: staleTime and gcTime

Two settings control caching, and mixing them up is the most common source of confusion:

  • staleTime (default 0): how long data counts as fresh. Fresh data is served from cache without refetching. With the default, data is stale immediately and refetches in the background on events like window focus.

  • gcTime (default 5 minutes): how long unused data stays in the cache before it is garbage-collected. It was called cacheTime before v5.

useQuery({
queryKey: ['users'],
queryFn: fetchUsers,
staleTime: 60 * 1000, // treat data as fresh for one minute
});

For data that rarely changes, such as a list of countries, a long staleTime saves many unnecessary requests.

Mutations: creating and updating data

Use useMutation for anything that changes data on the server, then invalidate the related queries so they refetch:

import { useMutation, useQueryClient } from '@tanstack/react-query';

async function addUser(newUser: { name: string }): Promise<User> {
const res = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newUser),
});
if (!res.ok) throw new Error('Failed to add user');
return res.json();
}

function AddUserButton() {
const queryClient = useQueryClient();

const mutation = useMutation({
mutationFn: addUser,
onSuccess: () => {
// Mark every query whose key starts with ['users'] as stale and refetch it
queryClient.invalidateQueries({ queryKey: ['users'] });
},
});

return (
<button onClick={() => mutation.mutate({ name: 'Ashish' })} disabled={mutation.isPending}>
{mutation.isPending ? 'Adding...' : 'Add user'}
</button>
);
}

Invalidation matches by prefix, so { queryKey: ['users'] } also refreshes ['users', 5].

Pagination without flicker

When the page number is part of the key, each page is cached separately. Use placeholderData to keep showing the previous page while the next one loads:

import { keepPreviousData, useQuery } from '@tanstack/react-query';

const { data, isPlaceholderData } = useQuery({
queryKey: ['users', { page }],
queryFn: () => fetchUsersPage(page),
placeholderData: keepPreviousData,
});

DevTools

The DevTools panel shows every query, its key, status and cached data, which makes caching behaviour easy to understand:

npm install @tanstack/react-query-devtools
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';

<QueryClientProvider client={queryClient}>
<YourRoutesOrApp />
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>

The DevTools are left out of production builds automatically.

Common beginner mistakes

  • Using v4 syntax in v5. v5 only accepts objects: useQuery({ queryKey, queryFn }) and invalidateQueries({ queryKey: ['users'] }). The old array forms throw errors.

  • Copying query data into useState. You lose automatic updates. Read from data directly, or derive values from it.

  • Leaving variables out of the key. If the query uses userId but the key is just ['user'], every user shares one cache entry.

  • Not throwing on HTTP errors. fetch resolves even for 404 and 500 responses.

  • Creating the QueryClient inside a component without useState, which creates a new, empty cache on every render.

Conclusion

TanStack Query takes data fetching out of your components: you describe what data you need with a key and a function, and it handles caching, refetching and loading states. Start with useQuery and useMutation, learn the difference between staleTime and gcTime, and open the DevTools whenever caching surprises you.

To see TanStack Query in a larger, typed codebase, read Building Scalable React Apps with TypeScript. For the full API, see the official TanStack Query documentation. Need a React or Next.js app built? See my web app development services.

Frequently Asked Questions

Is TanStack Query the same as React Query?

Yes. React Query was renamed TanStack Query in version 4, when it expanded beyond React to frameworks such as Vue, Solid and Svelte. For React you install the @tanstack/react-query package.

Does TanStack Query replace Redux?

For server data, usually yes: it handles fetching, caching, background refetching and loading and error states, which is most of what many apps used Redux for. You may still want a small client-state library such as Zustand for purely local UI state.

How do I install TanStack Query in a React app?

Run npm install @tanstack/react-query, create a QueryClient and wrap your app in a QueryClientProvider. You can then call useQuery to fetch data and useMutation to send it.

Share Article
Article Info
Published July 16, 2025
Web Development
4

Tags

tanstack queryreact queryreact data fetchingtanstack react query tutorialreact query examplestanstack query beginners guideuseQuery examplereact query mutationreact query vs useEffect
About the Author
AK
Ashish Kamat

Full-Stack Developer & Digital Marketer

View Profile
Stay Updated

Get the latest articles and tutorials delivered to your inbox.

Subscribe Now

Related Articles

Continue your learning journey with these related articles

Build an AI Powered Resume Builder with React and OpenAI API (Full Guide)
Web Development
November 20, 2025
5
Build an AI Powered Resume Builder with React and OpenAI API (Full Guide)

Build an AI resume builder with React and the OpenAI API, with your API key kept safely on a small server. Covers app structure, prompts for ATS-friendly content, JSON mode, live preview and PDF export.

reactopenai+7
Read Article

Need Help with Your Website?

I design and build fast, SEO-ready websites and apps for businesses across Nepal. Let's discuss your project.