SkillPilotAI

TanStack Query part 1

TanStack Query is an async state manager for server state. useQuery caches data by query key, removes duplicate requests, retries failures and refetches stale data in the background, replacing the useEffect + three useState pattern.

48.1 Why is it used?

  • Fetching in useEffect needs separate data, loading and error states in every component.
  • The same component used twice sends two requests; coming back from Cart shows Loading and a third request.
  • Server data is a remote copy that can go stale; you would have to write retry, race condition and refetch logic yourself.
React (JSX)
export function Products() {  const [data, setData] = useState(null);  const [loading, setLoading] = useState(true);  const [error, setError] = useState(null);  useEffect(() => {    fetch("/api/products")      .then((res) => res.json())      .then(setData)      .catch(setError)      .finally(() => setLoading(false));  }, []);  if (loading) return <p>Loading...</p>;  if (error) return <p>Error!</p>;  return <p>{data.join(", ")}</p>;}
Output
-- first render (used in 2 places) --Loading...Loading... -- data arrived --Shoes, Watch, BagShoes, Watch, BagNetwork: 2 requests -- back from Cart --Loading...Network: 3 requests
Problems with fetch in useEffect
  1. 1.Each component fetches its own copy

  2. 2.Same data: duplicate requests

  3. 3.No cache: Loading again on every visit

  4. 4.Retry, race conditions, refetch: all by hand

Server state needs a dedicated tool

48.2 Setup: QueryClientProvider

  • QueryClient holds the cache for the whole app and manages all queries.
  • Wrap App in <QueryClientProvider client={queryClient}> so every component can reach it, like a context.
Output
$ npm install @tanstack/react-query
React (JSX)
import { createRoot } from "react-dom/client";import {  QueryClient,  QueryClientProvider,} from "@tanstack/react-query";import { App } from "./App"; const queryClient = new QueryClient();const root = document.getElementById("root");createRoot(root).render(  <QueryClientProvider client={queryClient}>    <App />  </QueryClientProvider>);

48.3 Data with useQuery

  • queryKey: the unique name of this data, e.g. ["products"].
  • queryFn: the async function that actually fetches.
  • Returns data plus flags: isPending, isError, error.
  • No useState or useEffect needed.
React (JSX)
import { useQuery } from "@tanstack/react-query";import { fetchProducts } from "./api"; export function Products() {  const { data, isPending, isError, error } =    useQuery({      queryKey: ["products"],      queryFn: fetchProducts,    });   if (isPending) return <p>Loading...</p>;  if (isError) return <p>{error.message}</p>;  return <p>{data.join(", ")}</p>;}
Output
-- first load --Loading... -- data arrived --Shoes, Watch, Bag

48.4 How errors reach useQuery

  • fetch does not throw on 404 or 500, so check res.ok and throw yourself.
  • On error TanStack Query retries 3 times by default; then isError becomes true and error.message is shown.
JavaScript
export async function fetchProducts() {  const res = await fetch("/api/products");  if (!res.ok) {    throw new Error(`Error ${res.status}`);  }  return res.json();}
Output
-- loading --Loading... -- server returned 500 (after retries) --Error 500

48.5 Query keys: the cache address

  • A query key is an array that acts as the address of the data in the cache.
  • ["products", category] stores each category separately.
  • Key changes (shoes to watches): a new request goes out automatically.
  • Going back to shoes: data comes from the cache immediately, no Loading.
  • Two components with the same key share one request.
React (JSX)
import { useQuery } from "@tanstack/react-query";import { fetchByCategory } from "./api"; export function ProductList({ category }) {  const { data, isPending } = useQuery({    queryKey: ["products", category],    queryFn: () => fetchByCategory(category),  });   if (isPending) return <p>Loading...</p>;  return <p>{data.join(", ")}</p>;}
Output
-- category = shoes --Sneakers, Sandals -- changed to watches --Loading... -- watches loaded --Smartwatch, Analog -- back to shoes (from cache) --Sneakers, Sandals

48.6 staleTime and gcTime

  • Put options in a custom hook (useProducts) so every component uses the same setup.
  • staleTime: how long data counts as fresh. Default 0, so data is stale immediately and refetches on remount or window focus.
  • gcTime: how long unused (inactive) data stays in the cache. Default 5 minutes.
JavaScript
import { useQuery } from "@tanstack/react-query";import { fetchProducts } from "./api"; export function useProducts() {  return useQuery({    queryKey: ["products"],    queryFn: fetchProducts,    staleTime: 60_000, // 1 minute fresh    gcTime: 5 * 60_000, // default: 5 minutes  });}
OptionDefaultMeaning
staleTime0How long data is fresh; no refetch while fresh
gcTime5 minutesHow long inactive data stays in the cache before removal
retry3Retries of a failed queryFn before isError
refetchOnWindowFocustrueRefetch stale queries when the tab gets focus
The cache lifecycle
  1. 1.queryFn fetches, data stored under the key

  2. 2.Fresh: no request until staleTime passes

  3. 3.Stale: cached data shown immediately + background refetch

  4. 4.Inactive (no component uses it): removed after gcTime

48.7 Checkpoint: Loading or products?

  • staleTime is 0; the user goes to Cart and comes back within a minute.
  • Answer: the products, not Loading. Data is in the cache so isPending stays false; only isFetching is true during the background refetch.
  • isPending = no data yet; isFetching = any request in flight.
React (JSX)
export function Products() {  const { data, isPending, isFetching } =    useQuery({      queryKey: ["products"],      queryFn: fetchProducts,    });  if (isPending) return <p>Loading...</p>;  return (    <p>      {data.join(", ")}      {isFetching && " (updating...)"}    </p>  );}
Output
-- back within a minute (background refetch) --Shoes, Watch, Bag (updating...) -- refetch done --Shoes, Watch, Bag

48.8 Comparison: useEffect fetch vs useQuery

PointuseEffect + useStateuseQuery
State codedata, loading, error by handdata, isPending, isError, isFetching built in
CacheNoneBy query key
Duplicate requestsOne per componentDeduplicated for the same key
RetryWrite it yourself3 retries by default
FreshnessRefetch by handstaleTime + background refetch

48.9 Common mistakes

  • A variable used in queryFn but missing from queryKey: the key stays the same and old data (shoes) stays on screen.
  • Fix: every variable the queryFn uses goes into the queryKey.
  • Not throwing on !res.ok, so errors look like success.
  • Copying server data into useState or Zustand: two copies and the cache benefit is lost.
  • Myth: TanStack Query is a fetching library. It sends no request itself; your queryFn uses fetch, axios or anything.
React (JSX)
export function ProductList({ category }) {  const { data } = useQuery({    queryKey: ["products"],    queryFn: () => fetchByCategory(category),  });  return <p>{data?.join(", ")}</p>;}
React (JSX)
export function ProductList({ category }) {  const { data } = useQuery({    queryKey: ["products", category],    queryFn: () => fetchByCategory(category),  });  return <p>{data?.join(", ")}</p>;}

48.10 Best practices

  • All queryFn variables in the queryKey.
  • Throw on a failed response.
  • A custom hook per query (useProducts).
  • Set staleTime to suit the data.
  • Do not copy server data into other state.

48.11 Interview tips

  • TanStack Query is an async state manager for server state, not a fetching library.
  • It caches by query key, dedupes requests for the same key and retries failures.
  • staleTime decides when a refetch happens; gcTime decides how long unused data stays in the cache.
  • isPending vs isFetching: first load vs any background request.