Open History to see the last commit
1---
2id: useQuery
3title: useQuery
4---
5β
6```js
7const {
8 data,
9 dataUpdatedAt,
10 error,
11 errorUpdatedAt,
12 failureCount,
13 isError,
14 isFetched,
15 isFetchedAfterMount,
16 isFetching,
17 isPaused,
18 isLoading,
19 isLoadingError,
20 isPlaceholderData,
21 isPreviousData,
22 isRefetchError,
23 isRefetching,
24 isStale,
25 isSuccess,
26 refetch,
27 remove,
28 status,
29 fetchStatus,
30} = useQuery(queryKey, queryFn?, {
31 cacheTime,
32 enabled,
33 networkMode,
34 initialData,
35 initialDataUpdatedAt,
36 isDataEqual,
37 keepPreviousData,
38 meta,
39 notifyOnChangeProps,
40 onError,
41 onSettled,
42 onSuccess,
43 placeholderData,
44 queryKeyHashFn,
45 refetchInterval,
46 refetchIntervalInBackground,
47 refetchOnMount,
48 refetchOnReconnect,
49 refetchOnWindowFocus,
50 retry,
51 retryOnMount,
52 retryDelay,
53 select,
54 staleTime,
55 structuralSharing,
56 suspense,
57 useErrorBoundary,
58})
59β
60// or using the object syntax
61β
62const result = useQuery({
63 queryKey,
64 queryFn,
65 enabled,
66})
67```
68β
69**Options**
70β
71- `queryKey: unknown[]`
72 - **Required**
73 - The query key to use for this query.
74 - The query key will be hashed into a stable hash. See [Query Keys](../guides/query-keys) for more information.
75 - The query will automatically update when this key changes (as long as `enabled` is not set to `false`).
76- `queryFn: (context: QueryFunctionContext) => Promise<TData>`
77 - **Required, but only if no default query function has been defined** See [Default Query Function](../guides/default-query-function) for more information.
78 - The function that the query will use to request data.
79 - Receives a [QueryFunctionContext](../guides/query-functions#queryfunctioncontext)
80 - Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`.
81- `enabled: boolean`
82 - Set this to `false` to disable this query from automatically running.
83 - Can be used for [Dependent Queries](../guides/dependent-queries).
84- `networkMode: 'online' | 'always' | 'offlineFirst`
85 - optional
86 - defaults to `'online'`
87 - see [Network Mode](../guides/network-mode) for more information.
88- `retry: boolean | number | (failureCount: number, error: TError) => boolean`
89 - If `false`, failed queries will not retry by default.
90 - If `true`, failed queries will retry infinitely.
91 - If set to a `number`, e.g. `3`, failed queries will retry until the failed query count meets that number.
92- `retryOnMount: boolean`
93 - If set to `false`, the query will not be retried on mount if it contains an error. Defaults to `true`.
94- `retryDelay: number | (retryAttempt: number, error: TError) => number`
95 - This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds.
96 - A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff.
97 - A function like `attempt => attempt * 1000` applies linear backoff.
98- `staleTime: number | Infinity`
99 - Optional
100 - Defaults to `0`
101 - The time in milliseconds after data is considered stale. This value only applies to the hook it is defined on.
102 - If set to `Infinity`, the data will never be considered stale
103- `cacheTime: number | Infinity`
104 - Defaults to `5 * 60 * 1000` (5 minutes) or `Infinity` during SSR
105 - The time in milliseconds that unused/inactive cache data remains in memory. When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration. When different cache times are specified, the longest one will be used.
106 - If set to `Infinity`, will disable garbage collection
107- `queryKeyHashFn: (queryKey: QueryKey) => string`
108 - Optional
109 - If specified, this function is used to hash the `queryKey` to a string.
110- `refetchInterval: number | false | ((data: TData | undefined, query: Query) => number | false)`
111 - Optional
112 - If set to a number, all queries will continuously refetch at this frequency in milliseconds
113 - If set to a function, the function will be executed with the latest data and query to compute a frequency
114- `refetchIntervalInBackground: boolean`
115 - Optional
116 - If set to `true`, queries that are set to continuously refetch with a `refetchInterval` will continue to refetch while their tab/window is in the background
117- `refetchOnMount: boolean | "always" | ((query: Query) => boolean | "always")`
118 - Optional
119 - Defaults to `true`
120 - If set to `true`, the query will refetch on mount if the data is stale.
121 - If set to `false`, the query will not refetch on mount.
122 - If set to `"always"`, the query will always refetch on mount.
123 - If set to a function, the function will be executed with the query to compute the value
124- `refetchOnWindowFocus: boolean | "always" | ((query: Query) => boolean | "always")`
125 - Optional
126 - Defaults to `true`
127 - If set to `true`, the query will refetch on window focus if the data is stale.
128 - If set to `false`, the query will not refetch on window focus.
129 - If set to `"always"`, the query will always refetch on window focus.
130 - If set to a function, the function will be executed with the query to compute the value
131- `refetchOnReconnect: boolean | "always" | ((query: Query) => boolean | "always")`
132 - Optional
133 - Defaults to `true`
134 - If set to `true`, the query will refetch on reconnect if the data is stale.
135 - If set to `false`, the query will not refetch on reconnect.
136 - If set to `"always"`, the query will always refetch on reconnect.
137 - If set to a function, the function will be executed with the query to compute the value
138- `notifyOnChangeProps: string[] | "all"`
139 - Optional
140 - If set, the component will only re-render if any of the listed properties change.
141 - If set to `['data', 'error']` for example, the component will only re-render when the `data` or `error` properties change.
142 - If set to `"all"`, the component will opt-out of smart tracking and re-render whenever a query is updated.
143 - By default, access to properties will be tracked, and the component will only re-render when one of the tracked properties change.
144- `onSuccess: (data: TData) => void`
145 - Optional
146 - This function will fire any time the query successfully fetches new data.
147- `onError: (error: TError) => void`
148 - Optional
149 - This function will fire if the query encounters an error and will be passed the error.
150- `onSettled: (data?: TData, error?: TError) => void`
151 - Optional
152 - This function will fire any time the query is either successfully fetched or errors and be passed either the data or error
153- `select: (data: TData) => unknown`
154 - Optional
155 - This option can be used to transform or select a part of the data returned by the query function.
156- `suspense: boolean`
157 - Optional
158 - Set this to `true` to enable suspense mode.
159 - When `true`, `useQuery` will suspend when `status === 'loading'`
160 - When `true`, `useQuery` will throw runtime errors when `status === 'error'`
161- `initialData: TData | () => TData`
162 - Optional
163 - If set, this value will be used as the initial data for the query cache (as long as the query hasn't been created or cached yet)
164 - If set to a function, the function will be called **once** during the shared/root query initialization, and be expected to synchronously return the initialData
165 - Initial data is considered stale by default unless a `staleTime` has been set.
166 - `initialData` **is persisted** to the cache
167- `initialDataUpdatedAt: number | (() => number | undefined)`
168 - Optional
169 - If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated.
170- `placeholderData: TData | () => TData`
171 - Optional
172 - If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `loading` data and no initialData has been provided.
173 - `placeholderData` is **not persisted** to the cache
174- `keepPreviousData: boolean`
175 - Optional
176 - Defaults to `false`
177 - If set, any previous `data` will be kept when fetching new data because the query key changed.
178- `structuralSharing: boolean`
179 - Optional
180 - Defaults to `true`
181 - If set to `false`, structural sharing between query results will be disabled.
182- `useErrorBoundary: undefined | boolean | (error: TError, query: Query) => boolean`
183 - Defaults to the global query config's `useErrorBoundary` value, which is `undefined`
184 - Set this to `true` if you want errors to be thrown in the render phase and propagate to the nearest error boundary
185 - Set this to `false` to disable `suspense`'s default behavior of throwing errors to the error boundary.
186 - If set to a function, it will be passed the error and the query, and it should return a boolean indicating whether to show the error in an error boundary (`true`) or return the error as state (`false`)
187- `meta: Record<string, unknown>`
188 - Optional
189 - If set, stores additional information on the query cache entry that can be used as needed. It will be accessible wherever the `query` is available, and is also part of the `QueryFunctionContext` provided to the `queryFn`.
190- `context?: React.Context<QueryClient | undefined>`
191 - Use this to use a custom React Query context. Otherwise, `defaultContext` will be used.
192β
193**Returns**
194β
195- `status: String`
196 - Will be:
197 - `loading` if the query is in a "hard" loading state. This means there is no cached data and the query is currently fetching, eg `isFetching === true`
198 - `error` if the query attempt resulted in an error. The corresponding `error` property has the error received from the attempted fetch
199 - `success` if the query has received a response with no errors and is ready to display its data. The corresponding `data` property on the query is the data received from the successful fetch or if the query's `enabled` property is set to `false` and has not been fetched yet `data` is the first `initialData` supplied to the query on initialization.
200- `isLoading: boolean`
201 - A derived boolean from the `status` variable above, provided for convenience.
202- `isSuccess: boolean`
203 - A derived boolean from the `status` variable above, provided for convenience.
204- `isError: boolean`
205 - A derived boolean from the `status` variable above, provided for convenience.
206- `isLoadingError: boolean`
207 - Will be `true` if the query failed while fetching for the first time.
208- `isRefetchError: boolean`
209 - Will be `true` if the query failed while refetching.
210- `data: TData`
211 - Defaults to `undefined`.
212 - The last successfully resolved data for the query.
213- `dataUpdatedAt: number`
214 - The timestamp for when the query most recently returned the `status` as `"success"`.
215- `error: null | TError`
216 - Defaults to `null`
217 - The error object for the query, if an error was thrown.
218- `errorUpdatedAt: number`
219 - The timestamp for when the query most recently returned the `status` as `"error"`.
220- `isStale: boolean`
221 - Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`.
222- `isPlaceholderData: boolean`
223 - Will be `true` if the data shown is the placeholder data.
224- `isPreviousData: boolean`
225 - Will be `true` when `keepPreviousData` is set and data from the previous query is returned.
226- `isFetched: boolean`
227 - Will be `true` if the query has been fetched.
228- `isFetchedAfterMount: boolean`
229 - Will be `true` if the query has been fetched after the component mounted.
230 - This property can be used to not show any previously cached data.
231- `fetchStatus: FetchStatus`
232 - `fetching`: Is `true` whenever the queryFn is executing, which includes initial `loading` as well as background refetches.
233 - `paused`: The query wanted to fetch, but has been `paused`.
234 - `idle`: The query is not fetching.
235 - see [Network Mode](../guides/network-mode) for more information.
236- `isFetching: boolean`
237 - A derived boolean from the `fetchStatus` variable above, provided for convenience.
238- `isPaused: boolean`
239 - A derived boolean from the `fetchStatus` variable above, provided for convenience.
240- `isRefetching: boolean`
241 - Is `true` whenever a background refetch is in-flight, which _does not_ include initial `loading`
242 - Is the same as `isFetching && !isLoading`
243- `failureCount: number`
244 - The failure count for the query.
245 - Incremented every time the query fails.
246 - Reset to `0` when the query succeeds.
247- `errorUpdateCount: number`
248 - The sum of all errors.
249- `refetch: (options: { throwOnError: boolean, cancelRefetch: boolean }) => Promise<UseQueryResult>`
250 - A function to manually refetch the query.
251 - If the query errors, the error will only be logged. If you want an error to be thrown, pass the `throwOnError: true` option
252 - `cancelRefetch?: boolean`
253 - Defaults to `true`
254 - Per default, a currently running request will be cancelled before a new request is made
255 - When set to `false`, no refetch will be made if there is already a request running.
256- `remove: () => void`
257 - A function to remove the query from the cache.