Open History to see the last commit
1---
2id: queries
3title: Queries
4---
5β
6## Query Basics
7β
8A query is a declarative dependency on an asynchronous source of data that is tied to a **unique key**. A query can be used with any Promise based method (including GET and POST methods) to fetch data from a server. If your method modifies data on the server, we recommend using [Mutations](./mutations.md) instead.
9β
10[//]: # 'SubscribeDescription'
11β
12To subscribe to a query in your components or custom hooks, call the `useQuery` hook with at least:
13β
14[//]: # 'SubscribeDescription'
15β
16- A **unique key for the query**
17- A function that returns a promise that:
18 - Resolves the data, or
19 - Throws an error
20β
21[//]: # 'Example'
22β
23```tsx
24import { useQuery } from '@tanstack/react-query'
25β
26function App() {
27 const info = useQuery({ queryKey: ['todos'], queryFn: fetchTodoList })
28}
29```
30β
31[//]: # 'Example'
32β
33The **unique key** you provide is used internally for refetching, caching, and sharing your queries throughout your application.
34β
35The query result returned by `useQuery` contains all of the information about the query that you'll need for templating and any other usage of the data:
36β
37[//]: # 'Example2'
38β
39```tsx
40const result = useQuery({ queryKey: ['todos'], queryFn: fetchTodoList })
41```
42β
43[//]: # 'Example2'
44β
45The `result` object contains a few very important states you'll need to be aware of to be productive. A query can only be in one of the following states at any given moment:
46β
47- `isPending` or `status === 'pending'` - The query has no data yet
48- `isError` or `status === 'error'` - The query encountered an error
49- `isSuccess` or `status === 'success'` - The query was successful and data is available
50β
51Beyond those primary states, more information is available depending on the state of the query:
52β
53- `error` - If the query is in an `isError` state, the error is available via the `error` property.
54- `data` - If the query is in an `isSuccess` state, the data is available via the `data` property.
55- `isFetching` - In any state, if the query is fetching at any time (including background refetching) `isFetching` will be `true`.
56β
57For **most** queries, it's usually sufficient to check for the `isPending` state, then the `isError` state, then finally, assume that the data is available and render the successful state:
58β
59[//]: # 'Example3'
60β
61```tsx
62function Todos() {
63 const { isPending, isError, data, error } = useQuery({
64 queryKey: ['todos'],
65 queryFn: fetchTodoList,
66 })
67β
68 if (isPending) {
69 return <span>Loading...</span>
70 }
71β
72 if (isError) {
73 return <span>Error: {error.message}</span>
74 }
75β
76 // We can assume by this point that `isSuccess === true`
77 return (
78 <ul>
79 {data.map((todo) => (
80 <li key={todo.id}>{todo.title}</li>
81 ))}
82 </ul>
83 )
84}
85```
86β
87[//]: # 'Example3'
88β
89If booleans aren't your thing, you can always use the `status` state as well:
90β
91[//]: # 'Example4'
92β
93```tsx
94function Todos() {
95 const { status, data, error } = useQuery({
96 queryKey: ['todos'],
97 queryFn: fetchTodoList,
98 })
99β
100 if (status === 'pending') {
101 return <span>Loading...</span>
102 }
103β
104 if (status === 'error') {
105 return <span>Error: {error.message}</span>
106 }
107β
108 // also status === 'success', but "else" logic works, too
109 return (
110 <ul>
111 {data.map((todo) => (
112 <li key={todo.id}>{todo.title}</li>
113 ))}
114 </ul>
115 )
116}
117```
118β
119[//]: # 'Example4'
120β
121TypeScript will also narrow the type of `data` correctly if you've checked for `pending` and `error` before accessing it.
122β
123### FetchStatus
124β
125In addition to the `status` field, you will also get an additional `fetchStatus` property with the following options:
126β
127- `fetchStatus === 'fetching'` - The query is currently fetching.
128- `fetchStatus === 'paused'` - The query wanted to fetch, but it is paused. Read more about this in the [Network Mode](./network-mode.md) guide.
129- `fetchStatus === 'idle'` - The query is not doing anything at the moment.
130β
131### Why two different states?
132β
133Background refetches and stale-while-revalidate logic make all combinations for `status` and `fetchStatus` possible. For example:
134β
135- a query in `success` status will usually be in `idle` fetchStatus, but it could also be in `fetching` if a background refetch is happening.
136- a query that mounts and has no data will usually be in `pending` status and `fetching` fetchStatus, but it could also be `paused` if there is no network connection.
137β
138So keep in mind that a query can be in `pending` state without actually fetching data. As a rule of thumb:
139β
140- The `status` gives information about the `data`: Do we have any or not?
141- The `fetchStatus` gives information about the `queryFn`: Is it running or not?
142β
143[//]: # 'Materials'
144β
145## Further Reading
146β
147For an alternative way of performing status checks, have a look at [this article by TkDodo](https://tkdodo.eu/blog/status-checks-in-react-query).
148β
149[//]: # 'Materials'