TanStack Query fundamentals

Intermediate · 25 min

useQuery, query keys, staleTime and gcTime, and the automatic refetching that makes TanStack Query's cache actually stay fresh.

Before thisThe case for a data-fetching libraryCustom hooks

Web Dev Simplified · 25 min · from 0:44

TanStack Query fundamentals

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Web Dev SimplifiedReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • useQuery takes a query key and a function that returns a promise, and gives back data, isLoading, isError, and more — the fetch, cache read, and cache write all happen inside the hook.
  • The query key is not a label. It is the cache's lookup key, and two components calling useQuery with the same key read and write the exact same cache entry, which is how deduplication and cross-component sharing happen for free.
  • staleTime controls how long cached data is trusted without a background refetch; gcTime controls how long an unused cache entry is kept around before being thrown away. They answer two different questions and default to very different values.
  • TanStack Query refetches automatically on window focus and on network reconnect by default, which is exactly the behavior the previous lesson said you'd otherwise have to build yourself.
  • A query key should include every variable the query depends on, such as an id or a filter, because the cache treats a different key as a completely different entry with its own data and its own staleness clock.

From a promise to a cache entry

The previous lesson argued that server data needs a shared cache, not a private useState. useQuery is the hook that reads from and writes to that cache:

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

function fetchProduct(id) {
  return fetch(`/api/products/${id}`).then((res) => {
    if (!res.ok) throw new Error("Failed to load product");
    return res.json();
  });
}

function ProductPage({ id }) {
  const { data, isLoading, isError } = useQuery({
    queryKey: ["product", id],
    queryFn: () => fetchProduct(id),
  });

  if (isLoading) return <Spinner />;
  if (isError) return <ErrorMessage />;
  return <ProductCard product={data} />;
}

Compare this to the hand-rolled version from the last lesson. There’s no useState, no useEffect, no cleanup flag. useQuery owns all of that internally — it fires queryFn, tracks loading and error state, and stores the result under queryKey in a cache that lives outside any single component.

Query keys are the whole mechanism

The key, ["product", id], is not decoration. It’s a lookup key into a Map-like cache that TanStack Query maintains for the entire app. Any component — anywhere in the tree — that calls useQuery with ["product", 7] reads and writes that same entry. That’s the mechanism behind two things the previous lesson asked for:

  • Sharing. A header widget and a detail page both showing product 7 share one cache entry instead of fetching independently.
  • Deduplication. If both mount at nearly the same moment, TanStack Query notices the in-flight request for that key and reuses it instead of firing a second one.

This also means the key must capture everything the query’s result depends on. useQuery({ queryKey: ["todos", { status: filter }], queryFn: () => fetchTodos(filter) }) needs filter in the key — if you write ["todos"] for every filter value, every filter shares one cache entry and the UI will show whichever filter’s data was fetched last, for every filter.

staleTime and gcTime: two different clocks

Two options control how long cached data is trusted:

  • staleTime (default: 0) — how long a cache entry is considered fresh. While fresh, useQuery serves it straight from the cache with no network call at all. Once it’s stale, the data is still shown immediately, but TanStack Query refetches in the background to update it.
  • gcTime (default: 5 minutes, previously called cacheTime) — how long an entry stays in memory after no component is using it, before it’s discarded entirely. This is cleanup, not freshness.
useQuery({
  queryKey: ["product", id],
  queryFn: () => fetchProduct(id),
  staleTime: 60_000, // trust this data for 60 seconds before refetching
  gcTime: 5 * 60_000, // keep it cached for 5 minutes after it's unused
});

With staleTime: 0, every mount of a component using this key triggers a background refetch even if cached data renders instantly — which is a reasonable default for data that changes often, and the reason you’ll tune staleTime up for data that rarely changes, like a list of countries.

Refetching happens without you asking

This is the direct payoff of the previous lesson’s complaint about stale data. By default, TanStack Query refetches a query automatically when:

  • the browser window regains focus (refetchOnWindowFocus),
  • the network reconnects after being offline (refetchOnReconnect),
  • a component mounts and the data is stale (refetchOnMount).

None of this is something you wire up. It’s on by default, and it’s exactly the set of “someone changed the data elsewhere” moments that a plain useEffect fetch has no way to notice.

What the video covers

This lesson uses roughly the first half-hour of Web Dev Simplified’s full React Query tutorial (0:44–26:10): setup, a first useQuery call, and a dedicated “useQuery Basics” chapter covering query keys, loading/error/stale state, and refetch behavior in real detail. The rest of that video — useMutation, pagination, prefetching — belongs to the next lesson and beyond, so stop at the useMutation chapter. It doesn’t use the exact terms staleTime and gcTime as consistently as this lesson does; treat the section above as the vocabulary to attach to what you watch.

Where this fits

The next lesson is caching, invalidation, and mutations, where you’ll write data back to the server and tell the cache it needs to update.

Check yourself

  1. 01If two components both call useQuery(['product', 7], fetchProduct) at the same time, how many network requests actually go out?

    One. Both components are reading and writing the same cache entry because they used the same query key, so TanStack Query deduplicates the in-flight request and both components receive the same result.

  2. 02What is the practical difference between staleTime and gcTime?

    staleTime is how long fresh data is considered good enough to serve without refetching in the background; gcTime is how long a cache entry is kept in memory after nothing is using it anymore before it's garbage collected. Data can be stale but still cached, and cached but not currently rendered by anything.

  3. 03A query key is written as ['todos', { status: 'done' }] in one place and ['todos'] in another, for what is meant to be the same list. What breaks?

    TanStack Query treats these as two different cache entries, so filtering, invalidation, and refetching applied to one will not affect the other, and the UI can end up showing two different, disagreeing copies of what should be the same list.

  4. 04Without changing any code, why might a query refetch even though its component never re-rendered or remounted?

    TanStack Query refetches automatically when the browser window regains focus or the network reconnects, by default, which is exactly the refetch-on-focus behavior that a hand-rolled useEffect fetch does not provide on its own.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark