Open History to see the last commit
1---
2id: useQuery
3title: useQuery
4redirect_from:
5 - framework/react/reference/useQuery
6---
7β
8## Call Signature
9β
10```ts
11function useQuery<TQueryFnData, TError, TData, TQueryKey>(options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): DefinedUseQueryResult<TData, TError>;
12```
13β
14Defined in: [packages/react-query/src/useQuery.ts:50](https://github.com/TanStack/query/blob/main/packages/react-query/src/useQuery.ts#L50)
15β
16This overload is selected when `initialData` is set, so the resulting `data` is never `undefined`.
17β
18### Type Parameters
19β
20#### TQueryFnData
21β
22`TQueryFnData` = `unknown`
23β
24#### TError
25β
26`TError` = `Error`
27β
28#### TData
29β
30`TData` = `TQueryFnData`
31β
32#### TQueryKey
33β
34`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
35β
36### Parameters
37β
38#### options
39β
40[`DefinedInitialDataOptions`](../type-aliases/DefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
41β
42The [DefinedInitialDataOptions](../type-aliases/DefinedInitialDataOptions.md) to use β everything you can pass to `useQuery`, with `initialData` set.
43β
44#### queryClient?
45β
46[`QueryClient`](../classes/QueryClient.md)
47β
48Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
49be used.
50β
51### Returns
52β
53[`DefinedUseQueryResult`](../type-aliases/DefinedUseQueryResult.md)\<`TData`, `TError`\>
54β
55The current query result, typed so that `status` is `success` β or `error` if a fetch attempt
56fails while keeping the existing data (`status` never resolves to `pending` in this overload's type,
57since `initialData` guarantees data upfront). `isSuccess`/`isError` are derived booleans for convenience.
58β
59### See
60β
61[queryOptions](queryOptions.md) to share these options between `useQuery` and imperative APIs like `queryClient.query`.
62β
63### Example
64β
65```tsx
66import { useQuery } from '@tanstack/react-query'
67β
68function Posts() {
69 // `data` is `Post[]`, never `undefined`, thanks to `initialData` β even if a refetch fails,
70 // so the list stays visible alongside the error.
71 const { data, isError, error } = useQuery({
72 queryKey: ['posts'],
73 queryFn: fetchPosts,
74 initialData: [],
75 })
76β
77 return (
78 <div>
79 {isError ? <span>Error: {error.message}</span> : null}
80 <ul>
81 {data.map((post) => <li key={post.id}>{post.title}</li>)}
82 </ul>
83 </div>
84 )
85}
86```
87β
88## Call Signature
89β
90```ts
91function useQuery<TQueryFnData, TError, TData, TQueryKey>(options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): UseQueryResult<TData, TError>;
92```
93β
94Defined in: [packages/react-query/src/useQuery.ts:117](https://github.com/TanStack/query/blob/main/packages/react-query/src/useQuery.ts#L117)
95β
96### Type Parameters
97β
98#### TQueryFnData
99β
100`TQueryFnData` = `unknown`
101β
102#### TError
103β
104`TError` = `Error`
105β
106#### TData
107β
108`TData` = `TQueryFnData`
109β
110#### TQueryKey
111β
112`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
113β
114### Parameters
115β
116#### options
117β
118[`UndefinedInitialDataOptions`](../type-aliases/UndefinedInitialDataOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
119β
120The [UndefinedInitialDataOptions](../type-aliases/UndefinedInitialDataOptions.md) to use β everything you can pass to `useQuery`.
121β
122#### queryClient?
123β
124[`QueryClient`](../classes/QueryClient.md)
125β
126Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
127be used.
128β
129### Returns
130β
131[`UseQueryResult`](../type-aliases/UseQueryResult.md)\<`TData`, `TError`\>
132β
133The current query result. `status` is `pending` if there is no cached data to display, `error` if
134the last fetch attempt failed, or `success` if the query has data to display. `isPending`/`isSuccess`/`isError`
135are derived booleans for convenience.
136β
137### See
138β
139[queryOptions](queryOptions.md) to share these options between `useQuery` and imperative APIs like `queryClient.query`.
140β
141### Examples
142β
143```tsx
144import { useQuery } from '@tanstack/react-query'
145β
146function Posts() {
147 const { status, data, error, isFetching } = useQuery({
148 queryKey: ['posts'],
149 queryFn: fetchPosts,
150 })
151β
152 if (status === 'pending') return 'Loading...'
153 if (status === 'error') return <span>Error: {error.message}</span>
154β
155 return (
156 <div>
157 <ul>
158 {data.map((post) => (
159 <li key={post.id}>{post.title}</li>
160 ))}
161 </ul>
162 <div>{isFetching ? 'Background Updating...' : ' '}</div>
163 </div>
164 )
165}
166```
167β
168The same query, checking `isPending`/`isError` instead of `status` β pick whichever reads better to you:
169```tsx
170import { useQuery } from '@tanstack/react-query'
171β
172function Posts() {
173 const { isPending, isError, data, error } = useQuery({
174 queryKey: ['posts'],
175 queryFn: fetchPosts,
176 })
177β
178 if (isPending) return 'Loading...'
179 if (isError) return <span>Error: {error.message}</span>
180β
181 return (
182 <ul>
183 {data.map((post) => <li key={post.id}>{post.title}</li>)}
184 </ul>
185 )
186}
187```
188β
189## Call Signature
190β
191```ts
192function useQuery<TQueryFnData, TError, TData, TQueryKey>(options: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): UseQueryResult<TData, TError>;
193```
194β
195Defined in: [packages/react-query/src/useQuery.ts:281](https://github.com/TanStack/query/blob/main/packages/react-query/src/useQuery.ts#L281)
196β
197### Type Parameters
198β
199#### TQueryFnData
200β
201`TQueryFnData` = `unknown`
202β
203#### TError
204β
205`TError` = `Error`
206β
207#### TData
208β
209`TData` = `TQueryFnData`
210β
211#### TQueryKey
212β
213`TQueryKey` *extends* readonly `unknown`[] = readonly `unknown`[]
214β
215### Parameters
216β
217#### options
218β
219[`UseQueryOptions`](../interfaces/UseQueryOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>
220β
221The [UseQueryOptions](../interfaces/UseQueryOptions.md) to use β everything you can pass to `useQuery`.
222β
223#### queryClient?
224β
225[`QueryClient`](../classes/QueryClient.md)
226β
227Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
228be used.
229β
230### Returns
231β
232[`UseQueryResult`](../type-aliases/UseQueryResult.md)\<`TData`, `TError`\>
233β
234The current query result. `status` is `pending` if there is no cached data to display, `error` if
235the last fetch attempt failed, or `success` if the query has data to display. `isPending`/`isSuccess`/`isError`
236are derived booleans for convenience.
237β
238### See
239β
240[queryOptions](queryOptions.md) to share these options between `useQuery` and imperative APIs like `queryClient.query`.
241β
242### Examples
243β
244```tsx
245import { useQuery } from '@tanstack/react-query'
246β
247function Posts() {
248 const { status, data, error, isFetching } = useQuery({
249 queryKey: ['posts'],
250 queryFn: fetchPosts,
251 })
252β
253 if (status === 'pending') return 'Loading...'
254 if (status === 'error') return <span>Error: {error.message}</span>
255β
256 return (
257 <div>
258 <ul>
259 {data.map((post) => (
260 <li key={post.id}>{post.title}</li>
261 ))}
262 </ul>
263 <div>{isFetching ? 'Background Updating...' : ' '}</div>
264 </div>
265 )
266}
267```
268β
269`select` derives whatever `data` a component needs from the cached value, without changing what's
270actually stored in the cache β the cache still holds the full `Post[]`, but `data` here is a `number`:
271```tsx
272import { useQuery } from '@tanstack/react-query'
273β
274function PostCount() {
275 const { data, isPending, isError, error } = useQuery({
276 queryKey: ['posts'],
277 queryFn: fetchPosts,
278 select: (posts) => posts.length,
279 })
280β
281 if (isPending) return 'Loading...'
282 if (isError) return <span>Error: {error.message}</span>
283β
284 return <span>{data} posts</span>
285}
286```
287β
288A dependent query, only enabled once `postId` is set β use `isLoading`, not `isPending`, so the
289loading state doesn't show while the query is disabled:
290```tsx
291import { useQuery } from '@tanstack/react-query'
292β
293function Post({ postId }: { postId: number | undefined }) {
294 const { data, isLoading, isError, error } = useQuery({
295 queryKey: ['post', postId],
296 queryFn: () => fetchPost(postId!),
297 enabled: postId != null,
298 })
299β
300 if (postId == null) return 'Select a post'
301 if (isLoading) return 'Loading...'
302 if (isError) return <span>Error: {error.message}</span>
303β
304 return <h1>{data?.title}</h1>
305}
306```
307β
308The same dependent query, type safe: `skipToken` disables the query without needing the
309non-null assertion above, since `queryFn` is only ever called when `postId` is defined.
310`refetch` doesn't work while `queryFn` is `skipToken` β use `enabled: false` instead if you
311need to trigger the query manually:
312```tsx
313import { skipToken, useQuery } from '@tanstack/react-query'
314β
315function Post({ postId }: { postId: number | undefined }) {
316 const { data, isLoading, isError, error } = useQuery({
317 queryKey: ['post', postId],
318 queryFn: postId != null ? () => fetchPost(postId) : skipToken,
319 })
320β
321 if (postId == null) return 'Select a post'
322 if (isLoading) return 'Loading...'
323 if (isError) return <span>Error: {error.message}</span>
324β
325 return <h1>{data?.title}</h1>
326}
327```
328β
329Seeding a detail query from an already-cached list, to skip the loading state:
330```tsx
331import { useQuery, useQueryClient } from '@tanstack/react-query'
332β
333function Post({ postId }: { postId: number }) {
334 const queryClient = useQueryClient()
335β
336 const { data, isError, error } = useQuery({
337 queryKey: ['post', postId],
338 queryFn: () => fetchPost(postId),
339 initialData: () =>
340 queryClient
341 .getQueryData<Array<Post>>(['posts'])
342 ?.find((post) => post.id === postId),
343 })
344β
345 if (isError) return <span>Error: {error.message}</span>
346β
347 return <h1>{data?.title}</h1>
348}
349```
350β
351Paginated data, keeping the previous page's data visible while the next page loads:
352```tsx
353import { keepPreviousData, useQuery } from '@tanstack/react-query'
354import { useState } from 'react'
355β
356function Posts() {
357 const [page, setPage] = useState(0)
358β
359 const { data, isPlaceholderData, isError, error } = useQuery({
360 queryKey: ['posts', page],
361 queryFn: () => fetchPosts(page),
362 placeholderData: keepPreviousData,
363 })
364β
365 if (isError) return <span>Error: {error.message}</span>
366β
367 return (
368 <div>
369 <ul>
370 {data?.map((post) => <li key={post.id}>{post.title}</li>)}
371 </ul>
372 <button
373 disabled={isPlaceholderData}
374 onClick={() => setPage((old) => old + 1)}
375 >
376 Next Page
377 </button>
378 </div>
379 )
380}
381```