Open History to see the last commit
1---
2id: useQuery
3title: useQuery
4---
5β
6```tsx
7const {
8 data,
9 dataUpdatedAt,
10 error,
11 errorUpdateCount,
12 errorUpdatedAt,
13 failureCount,
14 failureReason,
15 fetchStatus,
16 isError,
17 isFetched,
18 isFetchedAfterMount,
19 isFetching,
20 isInitialLoading,
21 isLoading,
22 isLoadingError,
23 isPaused,
24 isPending,
25 isPlaceholderData,
26 isRefetchError,
27 isRefetching,
28 isStale,
29 isSuccess,
30 isEnabled,
31 refetch,
32 status,
33} = useQuery(
34 {
35 queryKey,
36 queryFn,
37 gcTime,
38 enabled,
39 networkMode,
40 initialData,
41 initialDataUpdatedAt,
42 meta,
43 notifyOnChangeProps,
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 subscribed,
58 throwOnError,
59 },
60 queryClient,
61)
62```
63β
64**Parameter1 (Options)**
65β
66- `queryKey: unknown[]`
67 - **Required**
68 - The query key to use for this query.
69 - The query key will be hashed into a stable hash. See [Query Keys](../guides/query-keys.md) for more information.
70 - The query will automatically update when this key changes (as long as `enabled` is not set to `false`).
71- `queryFn: (context: QueryFunctionContext) => Promise<TData>`
72 - **Required, but only if no default query function has been defined** See [Default Query Function](../guides/default-query-function.md) for more information.
73 - The function that the query will use to request data.
74 - Receives a [QueryFunctionContext](../guides/query-functions.md#queryfunctioncontext)
75 - Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`.
76- `enabled: boolean | (query: Query) => boolean`
77 - Set this to `false` to disable this query from automatically running.
78 - Can be used for [Dependent Queries](../guides/dependent-queries.md).
79- `networkMode: 'online' | 'always' | 'offlineFirst'`
80 - optional
81 - defaults to `'online'`
82 - see [Network Mode](../guides/network-mode.md) for more information.
83- `retry: boolean | number | (failureCount: number, error: TError) => boolean`
84 - If `false`, failed queries will not retry by default.
85 - If `true`, failed queries will retry infinitely.
86 - If set to a `number`, e.g. `3`, failed queries will retry until the failed query count meets that number.
87 - If set to a function, it will be called with `failureCount` (starting at `0` for the first retry) and `error` to determine if a retry should be attempted.
88 - defaults to `3` on the client and `0` on the server
89- `retryOnMount: boolean | (query: Query) => boolean`
90 - If set to `false`, the query will not be retried on mount if it contains an error and has no data. Defaults to `true`.
91 - If set to a function, the function will be executed with the query to compute the value.
92- `retryDelay: number | (retryAttempt: number, error: TError) => number`
93 - This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds.
94 - A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff.
95 - A function like `attempt => attempt * 1000` applies linear backoff.
96- `staleTime: number | 'static' | ((query: Query) => number | 'static')`
97 - Optional
98 - Defaults to `0`
99 - The time in milliseconds after which data is considered stale. This value only applies to the hook it is defined on.
100 - If set to `Infinity`, the data will not be considered stale unless manually invalidated
101 - If set to a function, the function will be executed with the query to compute a `staleTime`.
102 - If set to `'static'`, the data will never be considered stale
103- `gcTime: 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 garbage collection times are specified, the longest one will be used.
106 - Note: the maximum allowed time is about [24 days](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value), although it is possible to work around this limit using [timeoutManager.setTimeoutProvider](../../../reference/timeoutManager.md#timeoutmanagersettimeoutprovider).
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 | ((query: Query) => number | false | undefined)`
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 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 (except when `staleTime: 'static'` is used).
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 (except when `staleTime: 'static'` is used).
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 (except when `staleTime: 'static'` is used).
138 - If set to a function, the function will be executed with the query to compute the value
139- `notifyOnChangeProps: string[] | "all" | (() => string[] | "all" | undefined)`
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 - If set to a function, the function will be executed to compute the list of properties.
145 - By default, access to properties will be tracked, and the component will only re-render when one of the tracked properties change.
146- `select: (data: TData) => unknown`
147 - Optional
148 - 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.
149 - The `select` function will only run if `data` changed, or if the reference to the `select` function itself changes. To optimize, wrap the function in `useCallback`.
150- `initialData: TData | () => TData`
151 - Optional
152 - 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)
153 - 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
154 - Initial data is considered stale by default unless a `staleTime` has been set.
155 - `initialData` **is persisted** to the cache
156- `initialDataUpdatedAt: number | (() => number | undefined)`
157 - Optional
158 - If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated.
159- `placeholderData: TData | (previousValue: TData | undefined, previousQuery: Query | undefined) => TData`
160 - Optional
161 - If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `pending` state.
162 - `placeholderData` is **not persisted** to the cache
163 - If you provide a function for `placeholderData`, as a first argument you will receive previously watched query data if available, and the second argument will be the complete previousQuery instance.
164- `structuralSharing: boolean | (oldData: unknown | undefined, newData: unknown) => unknown`
165 - Optional
166 - Defaults to `true`
167 - If set to `false`, structural sharing between query results will be disabled.
168 - 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.
169- `subscribed: boolean`
170 - Optional
171 - Defaults to `true`
172 - If set to `false`, this instance of `useQuery` will not be subscribed to the cache. This means it won't trigger the `queryFn` on its own, and it won't receive updates if data gets into cache by other means.
173- `throwOnError: undefined | boolean | (error: TError, query: Query) => boolean`
174 - Optional
175 - Defaults to `false`
176 - Set this to `true` if you want errors to be thrown in the render phase and propagate to the nearest error boundary
177 - 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`)
178- `meta: Record<string, unknown>`
179 - Optional
180 - 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`.
181β
182**Parameter2 (QueryClient)**
183β
184- `queryClient?: QueryClient`
185 - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.
186β
187**Returns**
188β
189- `status: QueryStatus`
190 - Will be:
191 - `pending` if there's no cached data and no query attempt was finished yet.
192 - `error` if the query attempt resulted in an error. The corresponding `error` property has the error received from the attempted fetch
193 - `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.
194- `isPending: boolean`
195 - A derived boolean from the `status` variable above, provided for convenience.
196- `isSuccess: boolean`
197 - A derived boolean from the `status` variable above, provided for convenience.
198- `isError: boolean`
199 - A derived boolean from the `status` variable above, provided for convenience.
200- `isLoadingError: boolean`
201 - Will be `true` if the query failed while fetching for the first time.
202- `isRefetchError: boolean`
203 - Will be `true` if the query failed while refetching.
204- `data: TData`
205 - Defaults to `undefined`.
206 - The last successfully resolved data for the query.
207- `dataUpdatedAt: number`
208 - The timestamp for when the query most recently returned the `status` as `"success"`.
209- `error: null | TError`
210 - Defaults to `null`
211 - The error object for the query, if an error was thrown.
212- `errorUpdatedAt: number`
213 - The timestamp for when the query most recently returned the `status` as `"error"`.
214- `isStale: boolean`
215 - Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`.
216- `isPlaceholderData: boolean`
217 - Will be `true` if the data shown is the placeholder data.
218- `isFetched: boolean`
219 - Will be `true` if the query has been fetched.
220- `isFetchedAfterMount: boolean`
221 - Will be `true` if the query has been fetched after the component mounted.
222 - This property can be used to not show any previously cached data.
223- `fetchStatus: FetchStatus`
224 - `fetching`: Is `true` whenever the queryFn is executing, which includes initial `pending` as well as background refetches.
225 - `paused`: The query wanted to fetch, but has been `paused`.
226 - `idle`: The query is not fetching.
227 - see [Network Mode](../guides/network-mode.md) for more information.
228- `isFetching: boolean`
229 - A derived boolean from the `fetchStatus` variable above, provided for convenience.
230- `isPaused: boolean`
231 - A derived boolean from the `fetchStatus` variable above, provided for convenience.
232- `isRefetching: boolean`
233 - Is `true` whenever a background refetch is in-flight, which _does not_ include initial `pending`
234 - Is the same as `isFetching && !isPending`
235- `isLoading: boolean`
236 - Is `true` whenever the first fetch for a query is in-flight
237 - Is the same as `isFetching && isPending`
238- `isInitialLoading: boolean`
239 - **deprecated**
240 - An alias for `isLoading`, will be removed in the next major version.
241- `isEnabled: boolean`
242 - Is `true` if this query observer is enabled, `false` otherwise.
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- `failureReason: null | TError`
248 - The failure reason for the query retry.
249 - Reset to `null` when the query succeeds.
250- `errorUpdateCount: number`
251 - The sum of all errors.
252- `refetch: (options: { throwOnError: boolean, cancelRefetch: boolean }) => Promise<UseQueryResult>`
253 - A function to manually refetch the query.
254 - If the query errors, the error will only be logged. If you want an error to be thrown, pass the `throwOnError: true` option
255 - `cancelRefetch?: boolean`
256 - Defaults to `true`
257 - Per default, a currently running request will be cancelled before a new request is made
258 - When set to `false`, no refetch will be made if there is already a request running.