Sub topic 3
Fetching data with useQuery
This chapter covers the useQuery hook, the main way to read server data in TanStack Query v5. It assumes you know JavaScript and TypeScript (including async/await and Promises), React function components and hooks, basic HTTP and fetch, and JSON APIs. It also assumes you have read the previous chapter on QueryClient and QueryClientProvider, because useQuery only works inside a provider.
What useQuery does
useQuery is a hook that subscribes a component to a piece of server data. You describe the data with two things:
- A query key, an array that identifies the data in the cache.
- A query function, an async function that fetches the data and returns a Promise.
The library runs the query function, stores the result in the cache under the key, and re-renders your component as the request moves from loading to success or error. If another component asks for the same key, it shares the cached entry. It does not send a second request, unless the cached data is stale, which a later chapter covers.
Compare this with a hand-written useEffect and useState pair. There you would manage the loading flag, the error value, cancellation, and duplicate requests yourself. useQuery does all of that.
A first query
The example below assumes the provider from the previous chapter wraps <Todos />.
import { useQuery } from '@tanstack/react-query'
type Todo = { id: number; title: string; done: boolean }
async function fetchTodos(): Promise<Todo[]> {
const res = await fetch('/api/todos')
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}
function Todos() {
const { data, isPending, isError, error } = useQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
})
if (isPending) return <p>Loading...</p>
if (isError) return <p>Something went wrong: {error.message}</p>
return (
<ul>
{data.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
)
}Note four things in this code:
- In v5,
useQuerytakes a single options object. The older positional forms, such asuseQuery(key, fn), no longer exist. queryKeyis['todos']. This is the cache address for the list.queryFnreturns a Promise ofTodo[]. TypeScript infers the type ofdatafrom it.- The component checks
isPendingandisErrorbefore it readsdata. After those two early returns, TypeScript narrowsdatatoTodo[], sodata.mapneeds no optional chaining.
The query function must throw on failure
This rule causes more bugs than any other in this chapter.
fetch does not reject on HTTP error statuses such as 404 or 500. It only rejects on network failures. If your query function does not check res.ok and throw, a 500 response is treated as a success, and data becomes whatever the error body parsed to.
TanStack Query decides that a query failed only when the query function throws or returns a rejected Promise. That is why the example contains this line:
if (!res.ok) throw new Error(`Request failed: ${res.status}`)HTTP clients such as Axios already reject on non-2xx statuses, so you do not need this check with them.
A query function also must not return undefined. In v5, returning undefined from a query function is treated as an error, because undefined is not valid cached data. Return null if you mean "no value".
What the hook returns
useQuery returns an object with many fields. These are the ones you will use most often.
| Field | Meaning |
|---|---|
| `data` | The last successfully resolved data, or `undefined` if there is none yet. |
| `error` | The error thrown by the last failed attempt, or `null`. |
| `isPending` | There is no data yet. |
| `isError` | The query is in the error state. |
| `isSuccess` | The query has data. |
| `isFetching` | A request is in flight, including background refetches. |
| `refetch` | A function that fetches again on demand. |
isPending and isFetching are not the same thing. isPending means "I have nothing to show". isFetching means "a request is running right now". After the first load, a background refetch sets isFetching to true while isPending stays false and data still holds the older value. The next chapter covers this distinction in detail. For now, remember that isLoading from v4 is not the same as isPending in v5. In v5, isLoading is isFetching && isPending, which is only true during the very first fetch.
Request flow
The diagram shows what happens when a component mounts with a query that has no cached data.
On the first render the hook returns immediately with isPending set to true. The fetch starts as a side effect. When the Promise resolves, the cache notifies every component that observes the key, and they re-render.
Passing parameters to the query function
Real queries usually depend on an argument, such as an id. Put the argument in the query key and use it in the query function, which you wrap in an arrow function.
import { useQuery } from '@tanstack/react-query'
type Todo = { id: number; title: string; done: boolean }
async function fetchTodo(id: number): Promise<Todo> {
const res = await fetch(`/api/todos/${id}`)
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}
function TodoDetail({ id }: { id: number }) {
const { data } = useQuery({
queryKey: ['todos', id],
queryFn: () => fetchTodo(id),
staleTime: 60 * 1000,
})
return <p>{data?.title}</p>
}Here the key ['todos', id] gives each todo its own cache entry. When the id prop changes, the key changes, and the hook switches to a different entry. If that entry is not cached, it fetches. The staleTime option keeps cached data fresh for one minute, so a second component that mounts with the same id in that window does not trigger a refetch. Query keys and staleTime each get their own chapter, so treat them here as tools you will meet again.
Because data can be undefined while the query is pending, this component reads data?.title. This is the other common style: instead of early returns, you render with optional chaining and let the output be empty until data arrives.
Common errors
- Treating a failed HTTP status as success. The cause is a missing
res.okcheck. Throw an error in the query function. - Reading
databefore checking status.dataisundefinedwhile pending. CheckisPendingfirst, or usedata?.. - Using a variable in
queryFnthat is not inqueryKey. The cache entry then does not change when the variable changes, and users see stale or wrong data. Every value the query function depends on belongs in the key. - Calling
useQueryoutside a provider. React throws an error saying that noQueryClientis set. Wrap the tree inQueryClientProvider. - Returning
undefinedfrom the query function. In v5 this is reported as an error. Returnnullor another real value. - Using v4 code. Positional arguments,
isLoadingfor first load, andcacheTimedo not carry over. In v5 the options are an object,isPendingreplaces most uses ofisLoading, andgcTimereplacescacheTime.
Exercises
Exercise
A query function calls fetch('/api/todos') and returns res.json() with no other checks. The server responds with status 500 and a JSON body {"message":"boom"}. What will isError be, and how do you fix it?
Show answer
isError will be false, and the query will be in the success state with data set to {"message":"boom"}. fetch only rejects on network failures, so the 500 response does not fail the query. Fix it by checking if (!res.ok) throw new Error(...) before calling res.json(). Then the query enters the error state and error holds the thrown error.
Exercise
A component renders useQuery({ queryKey: ['todos'], queryFn: () => fetchTodo(id) }). The id prop changes from 1 to 2, but the screen keeps showing todo 1. Why, and what is the fix?
Show answer
The key ['todos'] does not contain id, so both ids map to the same cache entry and the hook sees no reason to fetch again. Add the id to the key: queryKey: ['todos', id]. Each id then gets its own cache entry, and changing the prop triggers a fetch for the new one.
Exercise
Which of isPending and isFetching is true during a background refetch of data that is already in the cache, and why does it matter for the UI?
Show answer
isFetching is true, while isPending is false because cached data exists. This lets you keep showing the existing data and, if you want, add a small refresh indicator based on isFetching, instead of replacing the whole screen with a loading message.