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