Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

useQuery.md

219 lines10.2 KB

1---
2id: useQuery
3title: useQuery
4---
5​
6```js
7const {
8 data,
9 dataUpdatedAt,
10 error,
11 errorUpdatedAt,
12 failureCount,
13 isError,
14 isFetchedAfterMount,
15 isFetching,
16 isIdle,
17 isLoading,
18 isLoadingError,
19 isPlaceholderData,
20 isPreviousData,
21 isRefetchError,
22 isStale,
23 isSuccess,
24 refetch,
25 remove,
26 status,
27} = useQuery(queryKey, queryFn?, {
28 cacheTime,
29 enabled,
30 initialData,
31 initialDataUpdatedAt
32 isDataEqual,
33 keepPreviousData,
34 notifyOnChangeProps,
35 notifyOnChangePropsExclusions,
36 onError,
37 onSettled,
38 onSuccess,
39 queryKeyHashFn,
40 refetchInterval,
41 refetchIntervalInBackground,
42 refetchOnMount,
43 refetchOnReconnect,
44 refetchOnWindowFocus,
45 retry,
46 retryOnMount,
47 retryDelay,
48 select,
49 staleTime,
50 structuralSharing,
51 suspense,
52 useErrorBoundary,
53})
54​
55// or using the object syntax
56​
57const result = useQuery({
58 queryKey,
59 queryFn,
60 enabled,
61})
62```
63​
64**Options**
65​
66- `queryKey: string | 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) 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) for more information.
73 - The function that the query will use to request data.
74 - Receives a `QueryFunctionContext` object with the following variables:
75 - `queryKey: QueryKey`
76 - Must return a promise that will either resolves data or throws an error.
77- `enabled: boolean`
78 - Set this to `false` to disable this query from automatically running.
79 - Can be used for [Dependent Queries](../guides/dependent-queries).
80- `retry: boolean | number | (failureCount: number, error: TError) => boolean`
81 - If `false`, failed queries will not retry by default.
82 - If `true`, failed queries will retry infinitely.
83 - If set to an `number`, e.g. `3`, failed queries will retry until the failed query count meets that number.
84- `retryOnMount: boolean`
85 - If set to `false`, the query will not be retried on mount if it contains an error. Defaults to `true`.
86- `retryDelay: (retryAttempt: number) => number`
87 - This function receives a `retryAttempt` integer and returns the delay to apply before the next attempt in milliseconds.
88 - A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff.
89 - A function like `attempt => attempt * 1000` applies linear backoff.
90- `staleTime: number | Infinity`
91 - The time in milliseconds after data is considered stale. This value only applies to the hook it is defined on.
92 - If set to `Infinity`, the data will never be considered stale
93- `cacheTime: number | Infinity`
94 - 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.
95 - If set to `Infinity`, will disable garbage collection
96- `refetchInterval: false | number`
97 - Optional
98 - If set to a number, all queries will continuously refetch at this frequency in milliseconds
99- `refetchIntervalInBackground: boolean`
100 - Optional
101 - 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
102- `refetchOnMount: boolean | "always"`
103 - Optional
104 - Defaults to `true`
105 - If set to `true`, the query will refetch on mount if the data is stale.
106 - If set to `false`, the query will not refetch on mount.
107 - If set to `"always"`, the query will always refetch on mount.
108- `refetchOnWindowFocus: boolean | "always"`
109 - Optional
110 - Defaults to `true`
111 - If set to `true`, the query will refetch on window focus if the data is stale.
112 - If set to `false`, the query will not refetch on window focus.
113 - If set to `"always"`, the query will always refetch on window focus.
114- `refetchOnReconnect: boolean | "always"`
115 - Optional
116 - Defaults to `true`
117 - If set to `true`, the query will refetch on reconnect if the data is stale.
118 - If set to `false`, the query will not refetch on reconnect.
119 - If set to `"always"`, the query will always refetch on reconnect.
120- `notifyOnChangeProps: string[] | "tracked"`
121 - Optional
122 - If set, the component will only re-render if any of the listed properties change.
123 - If set to `['data', 'error']` for example, the component will only re-render when the `data` or `error` properties change.
124 - If set to `"tracked"`, access to properties will be tracked, and the component will only re-render when one of the tracked properties change.
125- `notifyOnChangePropsExclusions: string[]`
126 - Optional
127 - If set, the component will not re-render if any of the listed properties change.
128 - If set to `['isStale']` for example, the component will not re-render when the `isStale` property changes.
129- `onSuccess: (data: TData) => void`
130 - Optional
131 - This function will fire any time the query successfully fetches new data.
132- `onError: (error: TError) => void`
133 - Optional
134 - This function will fire if the query encounters an error and will be passed the error.
135- `onSettled: (data?: TData, error?: TError) => void`
136 - Optional
137 - This function will fire any time the query is either successfully fetched or errors and be passed either the data or error
138- `select: (data: TData) => unknown`
139 - Optional
140 - This option can be used to transform or select a part of the data returned by the query function.
141- `suspense: boolean`
142 - Optional
143 - Set this to `true` to enable suspense mode.
144 - When `true`, `useQuery` will suspend when `status === 'loading'`
145 - When `true`, `useQuery` will throw runtime errors when `status === 'error'`
146- `initialData: TData | () => TData`
147 - Optional
148 - 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)
149 - 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
150 - Initial data is considered stale by default unless a `staleTime` has been set.
151 - `initialData` **is persisted** to the cache
152- `initialDataUpdatedAt: number | (() => number | undefined)`
153 - Optional
154 - If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated.
155- `placeholderData: TData | () => TData`
156 - Optional
157 - 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.
158 - `placeholderData` is **not persisted** to the cache
159- `keepPreviousData: boolean`
160 - Optional
161 - Defaults to `false`
162 - If set, any previous `data` will be kept when fetching new data because the query key changed.
163- `structuralSharing: boolean`
164 - Optional
165 - Defaults to `true`
166 - If set to `false`, structural sharing between query results will be disabled.
167​
168**Returns**
169​
170- `status: String`
171 - Will be:
172 - `idle` if the query is idle. This only happens if a query is initialized with `enabled: false` and no initial data is available.
173 - `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`
174 - `error` if the query attempt resulted in an error. The corresponding `error` property has the error received from the attempted fetch
175 - `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.
176- `isIdle: boolean`
177 - A derived boolean from the `status` variable above, provided for convenience.
178- `isLoading: boolean`
179 - A derived boolean from the `status` variable above, provided for convenience.
180- `isSuccess: boolean`
181 - A derived boolean from the `status` variable above, provided for convenience.
182- `isError: boolean`
183 - A derived boolean from the `status` variable above, provided for convenience.
184- `isLoadingError: boolean`
185 - Will be `true` if the query failed while fetching for the first time.
186- `isRefetchError: boolean`
187 - Will be `true` if the query failed while refetching.
188- `data: TData`
189 - Defaults to `undefined`.
190 - The last successfully resolved data for the query.
191- `dataUpdatedAt: number`
192 - The timestamp for when the query most recently returned the `status` as `"success"`.
193- `error: null | TError`
194 - Defaults to `null`
195 - The error object for the query, if an error was thrown.
196- `errorUpdatedAt: number`
197 - The timestamp for when the query most recently returned the `status` as `"error"`.
198- `isStale: boolean`
199 - Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`.
200- `isPlaceholderData: boolean`
201 - Will be `true` if the data shown is the placeholder data.
202- `isPreviousData: boolean`
203 - Will be `true` when `keepPreviousData` is set and data from the previous query is returned.
204- `isFetchedAfterMount: boolean`
205 - Will be `true` if the query has been fetched after the component mounted.
206 - This property can be used to not show any previously cached data.
207- `isFetching: boolean`
208 - Defaults to `true` so long as `enabled` is set to `false`
209 - Will be `true` if the query is currently fetching, including background fetching.
210- `failureCount: number`
211 - The failure count for the query.
212 - Incremented every time the query fails.
213 - Reset to `0` when the query succeeds.
214- `refetch: (options: { throwOnError: boolean, cancelRefetch: boolean }) => Promise<UseQueryResult>`
215 - A function to manually refetch the query.
216 - If the query errors, the error will only be logged. If you want an error to be thrown, pass the `throwOnError: true` option
217 - If `cancelRefetch` is `true`, then the current request will be cancelled before a new request is made
218- `remove: () => void`
219 - A function to remove the query from the cache.