Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 38 ยท Getting Started

Your First Query with useQuery

Write your first useQuery call: query key, query function, data, loading and error handling, and see how much code the hook replaces compared with useEffect.

useQuery is the hook you will use most. You give it two required things: a query key that names the data and a query function that fetches it. It returns an object describing the current state of that data. In this lesson you build a small todo list, handle loading and errors, and compare the result with the hand-written approach.

The hand-written way

Here is what loading data looks like without a library. It is read-only, because we only want to read it, not run it.

JSX
function Todos() {
  const [todos, setTodos] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    let cancelled = false;
    fetch("/api/todos")
      .then((r) => r.json())
      .then((data) => { if (!cancelled) setTodos(data); })
      .catch((e) => { if (!cancelled) setError(e); })
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, []);

  // ...render
}

That is 15 lines before any UI, and it still has no caching, no retry, no refetch when the user returns to the tab, and it fetches again every time the component mounts. Every component that needs todos repeats it.

The same thing with useQuery

JSX
function Todos() {
  const { data, isPending, isError, error } = useQuery({
    queryKey: ["todos"],
    queryFn: fetchTodos,
  });
  // ...render
}

useQuery takes a single options object in v5 (the older positional form useQuery(key, fn) was removed). The result object has many fields; the ones you need first are:

Field Meaning
data The last successfully resolved value, or undefined
isPending There is no data yet (first load)
isError The last attempt failed and there is no data
error The thrown error, or null
isSuccess You have data
refetch A function that fetches again
isFetching A request is in flight right now, including background refetches

Here is a working example. The "server" is an in-memory array with a delay, so you can run it anywhere. Use the buttons to make the next request fail, then retry.

A todo list with useQuery

Try this: press "Break the server, then refetch". The refetch fails, so isError becomes true and error holds the message. Query still keeps the previous data in the result, but because our component checks isError first, it replaces the list with the error message. In real apps you often want to keep showing the old list and add an error banner instead. You will see how to combine the flags in Query Status and Fetch Status.

The query key and query function

queryKey must be an array. It uniquely identifies the data in the cache. Two useQuery calls with equal keys share one cache entry, which is the deduplication you saw earlier. Keys get a full lesson in Query Keys.

queryFn is called with a context object when Query needs the data. It must return a promise that resolves with the data or rejects with an error. Two rules matter:

  • Throw on failure. If your function returns normally, Query treats it as success. The fetch API does not reject on HTTP 404 or 500, so check response.ok yourself.
  • Never return undefined. In v5 a query function that resolves to undefined is treated as an error, because cached data of undefined is indistinguishable from "no data".
JSX
async function fetchTodos() {
  const response = await fetch("/api/todos");
  if (!response.ok) {
    throw new Error("Request failed with status " + response.status);
  }
  return response.json();
}

When does it fetch?

useQuery fetches automatically in these situations:

  1. When a component using the key mounts and there is no fresh data in the cache.
  2. When the window regains focus and the data is stale.
  3. When the network reconnects and the data is stale.
  4. When the query key changes (a new key is a new query).
  5. When you call refetch() or invalidate the query.

You never call the query function yourself in the normal flow. You declare the dependency, and Query decides when a request is needed.

Seeing the cache work

Mount and unmount the same query and watch the request counter. The second time the component appears, the cached data shows instantly, then a background refetch updates it because the default staleTime is 0.

Cached data on remount

Hide the clock and show it again. There is no "loading" text the second time, because the cache still holds the data (it is kept for gcTime, five minutes by default). You see old data immediately while a fresh request runs. This pattern is called stale-while-revalidate, and it is the single biggest reason apps built with Query feel fast.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In TanStack Query v5, how do you call useQuery?

    v5 only accepts a single options object. The positional overloads from v3 and v4 were removed.
  2. 2. fetch('/api/x') returns a response with status 500. What happens inside a queryFn that just returns response.json()?

    fetch only rejects on network failures. You must throw for non-OK statuses yourself.
  3. 3. Which field is true only while there is no data yet?

    isPending means the query has no data. isFetching can also be true during a background refetch when data exists.
  4. 4. A component unmounts and mounts again two minutes later with default options. What does the user see?

    Unused data stays in memory for gcTime (5 minutes by default), and with staleTime 0 it refetches in the background on mount.

Summary

  • useQuery({ queryKey, queryFn }) returns the data and its state.
  • A queryFn must return a promise, throw on failure and never resolve to undefined.
  • Check response.ok yourself when using fetch.
  • Cached data shows instantly on remount while a background refetch runs (stale-while-revalidate).

Next: Query Status and Fetch Status