Mathesh

React Query

React Query for Beginners: Make Your App Feel Instant

What React Query is, why it beats fetch inside useEffect, and the handful of ideas you really need: queries, caching, stale time, instant detail pages, and mutations.

18 Nov 2026 React Query 7 min read 9 views

by MatheshCreator, Mathesh Biography

I share the stories behind my videos and the links that help you explore further.


In my reel I opened the same page twice. With a plain fetch in useEffect, the data took 1239 ms to appear. With React Query, it appeared in 31 ms. Same API, same data.

This post explains how, in plain language. You will learn what React Query is, how to use it, and the few ideas that matter most. You only need basic React: components, props, useState, and useEffect.

What is React Query?

React Query (now called TanStack Query) is a library that fetches, caches, and updates data from your API for you. You can find the official website and docs at tanstack.com/query.

The key idea is server state. Data from an API is not like normal React state. It lives on a server, you only hold a copy, it can change without you knowing, and fetching it takes time and can fail. React Query is built to manage exactly that.

The problem it solves

Fetching in useEffect looks simple, but you end up writing and maintaining all of this yourself:

  • Three pieces of state for every request: data, isLoading, and error.
  • A cleanup flag so you do not update state after the component unmounts.
  • No cache. Leave the page and come back, and the user sees a loader again, even though you had the data a moment ago.
  • Duplicate requests when two components need the same data.
  • No refresh when the user comes back to the tab.

React Query handles all of these. A 40-line useEffect component becomes about 15 lines.

Setup in two minutes

Install it:

BASH
bun add @tanstack/react-query
# or: npm install @tanstack/react-query

React Query keeps its cache in a QueryClient. Share it with your app through a provider. In the Next.js App Router, this must be a client component:

TSX
// app/providers.tsx
"use client";

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

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

  return (
    <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
  );
}

Wrap your app in <Providers> inside app/layout.tsx. Creating the client inside useState matters: it makes one cache and keeps it. A bare new QueryClient() in the component body would create an empty cache on every render.

Your first query

A query needs two things: a key (the name of the data in the cache) and a function that fetches it.

TSX
"use client";

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

type Link = { id: string; slug: string; clicks: number };

async function fetchLinks(): Promise<Link[]> {
  const res = await fetch("/api/links");
  if (!res.ok) throw new Error(`Request failed: ${res.status}`);
  return res.json();
}

export function Links() {
  const { data, isPending, isError } = useQuery({
    queryKey: ["links"],
    queryFn: fetchLinks,
  });

  if (isPending) return <p>Loading…</p>;
  if (isError) return <p>Something went wrong.</p>;

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

Two details to remember:

  • Check res.ok. fetch does not throw on a 404 or 500. If you skip the check, React Query thinks the request worked.
  • isPending means there is no data yet. isFetching means a request is running right now, even if you already have cached data. That difference is what lets you show old data instantly while new data loads.

How the cache works

Think of the cache as a notebook of answers you have already looked up. The query key is the label on each page.

TSX
useQuery({ queryKey: ["links"], queryFn: fetchLinks });
useQuery({ queryKey: ["link", id], queryFn: () => fetchLink(id) });

These are different pages in the notebook. Anything your fetch depends on, like an id or a filter, belongs in the key.

When a component asks for data that is already in the notebook, React Query does two things at once:

  1. It shows the saved answer immediately.
  2. It refreshes it in the background, and updates the screen if anything changed.

This is called stale-while-revalidate, and it is why apps feel fast. The user never stares at an empty screen.

Two settings control it:

SettingWhat it controlsDefault
staleTimeHow long data counts as fresh, so no refetch is needed0 (stale immediately)
gcTimeHow long unused data stays in the cache5 minutes

If your data rarely changes, set a longer staleTime to skip extra requests:

TSX
useQuery({
  queryKey: ["links"],
  queryFn: fetchLinks,
  staleTime: 60 * 1000, // no refetch for 1 minute
});

By default, stale data is also refetched when the window regains focus, when the network reconnects, and when a new component using the query mounts. Failed requests retry 3 times before reporting an error.

The trick behind my 31 ms result

Here is the real reason the second page was instant.

My app has a dashboard that lists every link, and a detail page for one link. The dashboard loads the list, so React Query already has every link in its cache. When you open a detail page, we can reuse that saved copy with initialData:

TSX
const queryClient = useQueryClient();

const { data: link } = useQuery({
  queryKey: ["link", id],
  queryFn: () => fetchLink(id),
  initialData: () =>
    queryClient.getQueryData<Link[]>(["links"])?.find((item) => item.id === id),
});

The detail page finds its link in memory and shows it on the first render. React Query still refetches in the background, so the data stays fresh. If the list is not cached, initialData returns undefined and a normal request runs, so it is safe to add.

Be honest about what this measures. React Query did not make the API faster. The API still takes 1.2 seconds. The page was instant because it skipped waiting for data it already had. That is a real win for your users, and that is the claim to make.

If the list only has part of the detail data, use placeholderData instead. It shows the preview but does not save it in the cache as if it were complete.

Changing data: mutations

useQuery reads data. useMutation writes it: create, update, or delete.

TSX
const queryClient = useQueryClient();

const mutation = useMutation({
  mutationFn: (input: { slug: string; target: string }) =>
    fetch("/api/links", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(input),
    }).then((res) => {
      if (!res.ok) throw new Error("Request failed");
      return res.json();
    }),
  onSuccess: () => {
    queryClient.invalidateQueries({ queryKey: ["links"] });
  },
});

// later, for example in a click handler:
mutation.mutate({ slug: "docs", target: "https://example.com/docs" });

After a write, your cached list is out of date. invalidateQueries marks it stale and refetches it if it is on screen, so the new link appears without any manual update code. Use mutation.isPending to disable the button while saving.

Mistakes beginners make

  1. Creating new QueryClient() during render. You lose the cache on every re-render. Create it once with useState.
  2. Not checking res.ok. React Query cannot see a failed request that fetch did not throw.
  3. Leaving variables out of the key. If your fetch uses id, the key must include id, or different records will share one cache entry.
  4. Mismatched keys when invalidating. invalidateQueries({ queryKey: ["links"] }) matches keys that start with ["links"]. It will not match ["link", id]. Name keys as a hierarchy, like ["links", "detail", id].
  5. Mixing up staleTime and gcTime. staleTime is how long data is fresh. gcTime is how long unused data is kept.

Cheat sheet

I want to…Use
Load and cache datauseQuery({ queryKey, queryFn })
Show a loader on the first loadisPending
Show "refreshing" during a background updateisFetching
Keep data fresh for longerstaleTime
Show a detail page instantly from a listinitialData (or placeholderData for a preview)
Create, update, or delete datauseMutation({ mutationFn })
Refresh the screen after a writequeryClient.invalidateQueries({ queryKey })

Where to go next

Try it on a real page of your own app. Put a one-second delay in an API route, build a list and a detail page, and watch the Network tab as you move between them. When you are comfortable, explore the Devtools panel, optimistic updates, pagination with useInfiniteQuery, and prefetching. The links below go straight to the official docs.

Keep exploring

Links & resources

More stories
React Query for Beginners: Make Your App Feel Instant | Mathesh Biography