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