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

migrating-to-react-query-4.md

529 lines23.9 KB

1---
2id: migrating-to-react-query-4
3title: Migrating to React Query 4
4---
5​
6## Breaking Changes
7​
8v4 is a major version, so there are some breaking changes to be aware of:
9​
10### react-query is now @tanstack/react-query
11​
12You will need to un-/install dependencies and change the imports:
13​
14```
15npm uninstall react-query
16npm install @tanstack/react-query
17npm install @tanstack/react-query-devtools
18```
19​
20```tsx
21- import { useQuery } from 'react-query' // [!code --]
22- import { ReactQueryDevtools } from 'react-query/devtools' // [!code --]
23​
24+ import { useQuery } from '@tanstack/react-query' // [!code ++]
25+ import { ReactQueryDevtools } from '@tanstack/react-query-devtools' // [!code ++]
26```
27​
28#### Codemod
29​
30To make the import migration easier, v4 comes with a codemod.
31​
32> The codemod is a best efforts attempt to help you migrate the breaking change. Please review the generated code thoroughly! Also, there are edge cases that cannot be found by the code mod, so please keep an eye on the log output.
33​
34You can easily apply it by using one (or both) of the following commands:
35​
36If you want to run it against `.js` or `.jsx` files, please use the command below:
37​
38```
39npx jscodeshift ./path/to/src/ \
40 --extensions=js,jsx \
41 --transform=./node_modules/@tanstack/react-query/codemods/v4/replace-import-specifier.js
42```
43​
44If you want to run it against `.ts` or `.tsx` files, please use the command below:
45​
46```
47npx jscodeshift ./path/to/src/ \
48 --extensions=ts,tsx \
49 --parser=tsx \
50 --transform=./node_modules/@tanstack/react-query/codemods/v4/replace-import-specifier.js
51```
52​
53Please note in the case of `TypeScript` you need to use `tsx` as the parser; otherwise, the codemod won't be applied properly!
54​
55**Note:** Applying the codemod might break your code formatting, so please don't forget to run `prettier` and/or `eslint` after you've applied the codemod!
56​
57**Note:** The codemod will _only_ change the imports - you still have to install the separate devtools package manually.
58​
59### Query Keys (and Mutation Keys) need to be an Array
60​
61In v3, Query and Mutation Keys could be a String or an Array. Internally, React Query has always worked with Array Keys only, and we've sometimes exposed this to consumers. For example, in the `queryFn`, you would always get the key as an Array to make working with [Default Query Functions](../default-query-function.md) easier.
62​
63However, we have not followed this concept through to all apis. For example, when using the `predicate` function on [Query Filters](../filters.md) you would get the raw Query Key. This makes it difficult to work with such functions if you use Query Keys that are mixed Arrays and Strings. The same was true when using global callbacks.
64​
65To streamline all apis, we've decided to make all keys Arrays only:
66​
67```tsx
68;-useQuery('todos', fetchTodos) + // [!code --]
69 useQuery(['todos'], fetchTodos) // [!code ++]
70```
71​
72#### Codemod
73​
74To make this migration easier, we decided to deliver a codemod.
75​
76> The codemod is a best efforts attempt to help you migrate the breaking change. Please review the generated code thoroughly! Also, there are edge cases that cannot be found by the code mod, so please keep an eye on the log output.
77​
78You can easily apply it by using one (or both) of the following commands:
79​
80If you want to run it against `.js` or `.jsx` files, please use the command below:
81​
82```
83npx jscodeshift ./path/to/src/ \
84 --extensions=js,jsx \
85 --transform=./node_modules/@tanstack/react-query/codemods/v4/key-transformation.js
86```
87​
88If you want to run it against `.ts` or `.tsx` files, please use the command below:
89​
90```
91npx jscodeshift ./path/to/src/ \
92 --extensions=ts,tsx \
93 --parser=tsx \
94 --transform=./node_modules/@tanstack/react-query/codemods/v4/key-transformation.js
95```
96​
97Please note in the case of `TypeScript` you need to use `tsx` as the parser; otherwise, the codemod won't be applied properly!
98​
99**Note:** Applying the codemod might break your code formatting, so please don't forget to run `prettier` and/or `eslint` after you've applied the codemod!
100​
101### The idle state has been removed
102​
103With the introduction of the new [fetchStatus](../queries.md#fetchstatus) for better offline support, the `idle` state became irrelevant, because `fetchStatus: 'idle'` captures the same state better. For more information, please read [Why two different states](../queries.md#why-two-different-states).
104​
105This will mostly affect `disabled` queries that don't have any `data` yet, as those were in `idle` state before:
106​
107```tsx
108- status: 'idle' // [!code --]
109+ status: 'loading' // [!code ++]
110+ fetchStatus: 'idle' // [!code ++]
111```
112​
113Also, have a look at [the guide on dependent queries](../dependent-queries.md)
114​
115#### disabled queries
116​
117Due to this change, disabled queries (even temporarily disabled ones) will start in `loading` state. To make migration easier, especially for having a good flag to know when to display a loading spinner, you can check for `isInitialLoading` instead of `isLoading`:
118​
119```tsx
120;-isLoading + // [!code --]
121 isInitialLoading // [!code ++]
122```
123​
124See also the guide on [disabling queries](../disabling-queries.md#isInitialLoading)
125​
126### new API for `useQueries`
127​
128The `useQueries` hook now accepts an object with a `queries` prop as its input. The value of the `queries` prop is an array of queries (this array is identical to what was passed into `useQueries` in v3).
129​
130```tsx
131;-useQueries([
132 { queryKey1, queryFn1, options1 },
133 { queryKey2, queryFn2, options2 },
134]) + // [!code --]
135 useQueries({
136 queries: [
137 { queryKey1, queryFn1, options1 },
138 { queryKey2, queryFn2, options2 },
139 ],
140 }) // [!code ++]
141```
142​
143### Undefined is an illegal cache value for successful queries
144​
145In order to make bailing out of updates possible by returning `undefined`, we had to make `undefined` an illegal cache value. This is in-line with other concepts of react-query, for example, returning `undefined` from the [initialData function](../initial-query-data.md#initial-data-function) will also _not_ set data.
146​
147Further, it is an easy bug to produce `Promise<void>` by adding logging in the queryFn:
148​
149```tsx
150useQuery(['key'], () =>
151 axios.get(url).then((result) => console.log(result.data)),
153```
154​
155This is now disallowed on type level; at runtime, `undefined` will be transformed to a _failed Promise_, which means you will get an `error`, which will also be logged to the console in development mode.
156​
157### Queries and mutations, per default, need network connection to run
158​
159Please read the [New Features announcement](#proper-offline-support) about online / offline support, and also the dedicated page about [Network mode](../network-mode.md)
160​
161Even though React Query is an Async State Manager that can be used for anything that produces a Promise, it is most often used for data fetching in combination with data fetching libraries. That is why, per default, queries and mutations will be `paused` if there is no network connection. If you want to opt-in to the previous behavior, you can globally set `networkMode: offlineFirst` for both queries and mutations:
162​
163```tsx
164new QueryClient({
165 defaultOptions: {
166 queries: {
167 networkMode: 'offlineFirst',
168 },
169 mutations: {
170 networkMode: 'offlineFirst',
171 },
172 },
173})
174```
175​
176### `notifyOnChangeProps` property no longer accepts `"tracked"` as a value
177​
178The `notifyOnChangeProps` option no longer accepts a `"tracked"` value. Instead, `useQuery` defaults to tracking properties. All queries using `notifyOnChangeProps: "tracked"` should be updated by removing this option.
179​
180If you would like to bypass this in any queries to emulate the v3 default behavior of re-rendering whenever a query changes, `notifyOnChangeProps` now accepts an `"all"` value to opt-out of the default smart tracking optimization.
181​
182### `notifyOnChangePropsExclusion` has been removed
183​
184In v4, `notifyOnChangeProps` defaults to the `"tracked"` behavior of v3 instead of `undefined`. Now that `"tracked"` is the default behavior for v4, it no longer makes sense to include this config option.
185​
186### Consistent behavior for `cancelRefetch`
187​
188The `cancelRefetch` option can be passed to all functions that imperatively fetch a query, namely:
189​
190- `queryClient.refetchQueries`
191- `queryClient.invalidateQueries`
192- `queryClient.resetQueries`
193- `refetch` returned from `useQuery`
194- `fetchNextPage` and `fetchPreviousPage` returned from `useInfiniteQuery`
195​
196Except for `fetchNextPage` and `fetchPreviousPage`, this flag was defaulting to `false`, which was inconsistent and potentially troublesome: Calling `refetchQueries` or `invalidateQueries` after a mutation might not yield the latest result if a previous slow fetch was already ongoing, because this refetch would have been skipped.
197​
198We believe that if a query is actively refetched by some code you write, it should, per default, re-start the fetch.
199​
200That is why this flag now defaults to _true_ for all methods mentioned above. It also means that if you call `refetchQueries` twice in a row, without awaiting it, it will now cancel the first fetch and re-start it with the second one:
201​
202```
203queryClient.refetchQueries({ queryKey: ['todos'] })
204// this will abort the previous refetch and start a new fetch
205queryClient.refetchQueries({ queryKey: ['todos'] })
206```
207​
208You can opt-out of this behaviour by explicitly passing `cancelRefetch:false`:
209​
210```
211queryClient.refetchQueries({ queryKey: ['todos'] })
212// this will not abort the previous refetch - it will just be ignored
213queryClient.refetchQueries({ queryKey: ['todos'] }, { cancelRefetch: false })
214```
215​
216> Note: There is no change in behaviour for automatically triggered fetches, e.g. because a query mounts or because of a window focus refetch.
217​
218### Query Filters
219​
220A [query filter](../filters.md) is an object with certain conditions to match a query. Historically, the filter options have mostly been a combination of boolean flags. However, combining those flags can lead to impossible states. Specifically:
221​
222```
223active?: boolean
224 - When set to true it will match active queries.
225 - When set to false it will match inactive queries.
226inactive?: boolean
227 - When set to true it will match inactive queries.
228 - When set to false it will match active queries.
229```
230​
231Those flags don't work well when used together, because they are mutually exclusive. Setting `false` for both flags could match all queries, judging from the description, or no queries, which doesn't make much sense.
232​
233With v4, those filters have been combined into a single filter to better show the intent:
234​
235```tsx
236- active?: boolean // [!code --]
237- inactive?: boolean // [!code --]
238+ type?: 'active' | 'inactive' | 'all' // [!code ++]
239```
240​
241The filter defaults to `all`, and you can choose to only match `active` or `inactive` queries.
242​
243#### refetchActive / refetchInactive
244​
245[queryClient.invalidateQueries](../../../../reference/QueryClient.md#queryclientinvalidatequeries) had two additional, similar flags:
246​
247```
248refetchActive: Boolean
249 - Defaults to true
250 - When set to false, queries that match the refetch predicate and are actively being rendered
251 via useQuery and friends will NOT be refetched in the background, and only marked as invalid.
252refetchInactive: Boolean
253 - Defaults to false
254 - When set to true, queries that match the refetch predicate and are not being rendered
255 via useQuery and friends will be both marked as invalid and also refetched in the background
256```
257​
258For the same reason, those have also been combined:
259​
260```tsx
261- refetchActive?: boolean // [!code --]
262- refetchInactive?: boolean // [!code --]
263+ refetchType?: 'active' | 'inactive' | 'all' | 'none' // [!code ++]
264```
265​
266This flag defaults to `active` because `refetchActive` defaulted to `true`. This means we also need a way to tell `invalidateQueries` to not refetch at all, which is why a fourth option (`none`) is also allowed here.
267​
268### `onSuccess` is no longer called from `setQueryData`
269​
270This was confusing to many and also created infinite loops if `setQueryData` was called from within `onSuccess`. It was also a frequent source of error when combined with `staleTime`, because if data was read from the cache only, `onSuccess` was _not_ called.
271​
272Similar to `onError` and `onSettled`, the `onSuccess` callback is now tied to a request being made. No request -> no callback.
273​
274If you want to listen to changes of the `data` field, you can best do this with a `useEffect`, where `data` is part of the dependency Array. Since React Query ensures stable data through structural sharing, the effect will not execute with every background refetch, but only if something within data has changed:
275​
276```
277const { data } = useQuery({ queryKey, queryFn })
278React.useEffect(() => mySideEffectHere(data), [data])
279```
280​
281### `persistQueryClient` and the corresponding persister plugins are no longer experimental and have been renamed
282​
283The plugins `createWebStoragePersistor` and `createAsyncStoragePersistor` have been renamed to [`createSyncStoragePersister`](../../plugins/createSyncStoragePersister.md) and [`createAsyncStoragePersister`](../../plugins/createAsyncStoragePersister.md) respectively. The interface `Persistor` in `persistQueryClient` has also been renamed to `Persister`. Checkout [this stackexchange](https://english.stackexchange.com/questions/206893/persister-or-persistor) for the motivation of this change.
284​
285Since these plugins are no longer experimental, their import paths have also been updated:
286​
287```tsx
288- import { persistQueryClient } from 'react-query/persistQueryClient-experimental' // [!code --]
289- import { createWebStoragePersistor } from 'react-query/createWebStoragePersistor-experimental' // [!code --]
290- import { createAsyncStoragePersistor } from 'react-query/createAsyncStoragePersistor-experimental' // [!code --]
291​
292+ import { persistQueryClient } from '@tanstack/react-query-persist-client' // [!code ++]
293+ import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister' // [!code ++]
294+ import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister' // [!code ++]
295```
296​
297### The `cancel` method on promises is no longer supported
298​
299The [old `cancel` method](../query-cancellation.md#old-cancel-function) that allowed you to define a `cancel` function on promises, which was then used by the library to support query cancellation, has been removed. We recommend to use the [newer API](../query-cancellation.md) (introduced with v3.30.0) for query cancellation that uses the [`AbortController` API](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) internally and provides you with an [`AbortSignal` instance](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) for your query function to support query cancellation.
300​
301### TypeScript
302​
303Types now require using TypeScript v4.1 or greater
304​
305### Supported Browsers
306​
307As of v4, React Query is optimized for modern browsers. We have updated our browserslist to produce a more modern, performant and smaller bundle. You can read about the requirements [here](../../installation#requirements).
308​
309### `setLogger` is removed
310​
311It was possible to change the logger globally by calling `setLogger`. In v4, that function is replaced with an optional field when creating a `QueryClient`.
312​
313```tsx
314- import { QueryClient, setLogger } from 'react-query'; // [!code --]
315+ import { QueryClient } from '@tanstack/react-query'; // [!code ++]
316​
317- setLogger(customLogger) // [!code --]
318- const queryClient = new QueryClient(); // [!code --]
319+ const queryClient = new QueryClient({ logger: customLogger }) // [!code ++]
320```
321​
322### No _default_ manual Garbage Collection server-side
323​
324In v3, React Query would cache query results for a default of 5 minutes, then manually garbage collect that data. This default was applied to server-side React Query as well.
325​
326This lead to high memory consumption and hanging processes waiting for this manual garbage collection to complete. In v4, by default the server-side `cacheTime` is now set to `Infinity` effectively disabling manual garbage collection (the NodeJS process will clear everything once a request is complete).
327​
328This change only impacts users of server-side React Query, such as with Next.js. If you are setting a `cacheTime` manually this will not impact you (although you may want to mirror behavior).
329​
330### Logging in production
331​
332Starting with v4, react-query will no longer log errors (e.g. failed fetches) to the console in production mode, as this was confusing to many.
333Errors will still show up in development mode.
334​
335### ESM Support
336​
337React Query now supports [package.json `"exports"`](https://nodejs.org/api/packages.html#exports) and is fully compatible with Node's native resolution for both CommonJS and ESM. We don't expect this to be a breaking change for most users, but this restricts the files you can import into your project to only the entry points we officially support.
338​
339### Streamlined NotifyEvents
340​
341Subscribing manually to the `QueryCache` has always given you a `QueryCacheNotifyEvent`, but this was not true for the `MutationCache`. We have streamlined the behavior and also adapted event names accordingly.
342​
343#### QueryCacheNotifyEvent
344​
345```tsx
346- type: 'queryAdded' // [!code --]
347+ type: 'added' // [!code ++]
348- type: 'queryRemoved' // [!code --]
349+ type: 'removed' // [!code ++]
350- type: 'queryUpdated' // [!code --]
351+ type: 'updated' // [!code ++]
352```
353​
354#### MutationCacheNotifyEvent
355​
356The `MutationCacheNotifyEvent` uses the same types as the `QueryCacheNotifyEvent`.
357​
358> Note: This is only relevant if you manually subscribe to the caches via `queryCache.subscribe` or `mutationCache.subscribe`
359​
360### Separate hydration exports have been removed
361​
362With version [3.22.0](https://github.com/tannerlinsley/react-query/releases/tag/v3.22.0), hydration utilities moved into the React Query core. With v3, you could still use the old exports from `react-query/hydration`, but these exports have been removed with v4.
363​
364```tsx
365- import { dehydrate, hydrate, useHydrate, Hydrate } from 'react-query/hydration' // [!code --]
366+ import { dehydrate, hydrate, useHydrate, Hydrate } from '@tanstack/react-query' // [!code ++]
367```
368​
369### Removed undocumented methods from the `queryClient`, `query` and `mutation`
370​
371The methods `cancelMutations` and `executeMutation` on the `QueryClient` were undocumented and unused internally, so we removed them. Since it was just a wrapper around a method available on the `mutationCache`, you can still use the functionality of `executeMutation`
372​
373```tsx
374- executeMutation< // [!code --]
375- TData = unknown, // [!code --]
376- TError = unknown, // [!code --]
377- TVariables = void, // [!code --]
378- TContext = unknown // [!code --]
379- >( // [!code --]
380- options: MutationOptions<TData, TError, TVariables, TContext> // [!code --]
381- ): Promise<TData> { // [!code --]
382- return this.mutationCache.build(this, options).execute() // [!code --]
383- } // [!code --]
384```
385​
386Additionally, `query.setDefaultOptions` was removed because it was also unused. `mutation.cancel` was removed because it didn't actually cancel the outgoing request.
387​
388### The `src/react` directory was renamed to `src/reactjs`
389​
390Previously, React Query had a directory named `react` which imported from the `react` module. This could cause problems with some Jest configurations, resulting in errors when running tests like:
391​
392```
393TypeError: Cannot read property 'createContext' of undefined
394```
395​
396With the renamed directory this no longer is an issue.
397​
398If you were importing anything from `'react-query/react'` directly in your project (as opposed to just `'react-query'`), then you need to update your imports:
399​
400```tsx
401- import { QueryClientProvider } from 'react-query/react'; // [!code --]
402+ import { QueryClientProvider } from '@tanstack/react-query/reactjs'; // [!code ++]
403```
404​
405## New Features πŸš€
406​
407v4 comes with an awesome set of new features:
408​
409### Support for React 18
410​
411React 18 was released earlier this year, and v4 now has first class support for it and the new concurrent features it brings.
412​
413### Proper offline support
414​
415In v3, React Query has always fired off queries and mutations, but then taken the assumption that if you want to retry it, you need to be connected to the internet. This has led to several confusing situations:
416​
417- You are offline and mount a query - it goes to loading state, the request fails, and it stays in loading state until you go online again, even though it is not really fetching.
418- Similarly, if you are offline and have retries turned off, your query will just fire and fail, and the query goes to error state.
419- You are offline and want to fire off a query that doesn't necessarily need network connection (because you _can_ use React Query for something other than data fetching), but it fails for some other reason. That query will now be paused until you go online again.
420- Window focus refetching didn't do anything at all if you were offline.
421​
422With v4, React Query introduces a new `networkMode` to tackle all these issues. Please read the dedicated page about the new [Network mode](../network-mode) for more information.
423​
424### Tracked Queries per default
425​
426React Query defaults to "tracking" query properties, which should give you a nice boost in render optimization. The feature has existed since [v3.6.0](https://github.com/tannerlinsley/react-query/releases/tag/v3.6.0) and has now become the default behavior with v4.
427​
428### Bailing out of updates with setQueryData
429​
430When using the [functional updater form of setQueryData](../../../../reference/QueryClient.md#queryclientsetquerydata), you can now bail out of the update by returning `undefined`. This is helpful if `undefined` is given to you as `previousValue`, which means that currently, no cached entry exists and you don't want to / cannot create one, like in the example of toggling a todo:
431​
432```tsx
433queryClient.setQueryData(['todo', id], (previousTodo) =>
434 previousTodo ? { ...previousTodo, done: true } : undefined,
436```
437​
438### Mutation Cache Garbage Collection
439​
440Mutations can now also be garbage collected automatically, just like queries. The default `cacheTime` for mutations is also set to 5 minutes.
441​
442### Custom Contexts for Multiple Providers
443​
444Custom contexts can now be specified to pair hooks with their matching `Provider`. This is critical when there may be multiple React Query `Provider` instances in the component tree, and you need to ensure your hook uses the correct `Provider` instance.
445​
446An example:
447​
4481. Create a data package.
449​
450```tsx
451// Our first data package: @my-scope/container-data
452​
453const context = React.createContext<QueryClient | undefined>(undefined)
454const queryClient = new QueryClient()
455​
456export const useUser = () => {
457 return useQuery(USER_KEY, USER_FETCHER, {
458 context,
459 })
461​
462export const ContainerDataProvider = ({
463 children,
464}: {
465 children: React.ReactNode
466}) => {
467 return (
468 <QueryClientProvider client={queryClient} context={context}>
469 {children}
470 </QueryClientProvider>
471 )
473```
474​
4752. Create a second data package.
476​
477```tsx
478// Our second data package: @my-scope/my-component-data
479​
480const context = React.createContext<QueryClient | undefined>(undefined)
481const queryClient = new QueryClient()
482​
483export const useItems = () => {
484 return useQuery(ITEMS_KEY, ITEMS_FETCHER, {
485 context,
486 })
488​
489export const MyComponentDataProvider = ({
490 children,
491}: {
492 children: React.ReactNode
493}) => {
494 return (
495 <QueryClientProvider client={queryClient} context={context}>
496 {children}
497 </QueryClientProvider>
498 )
500```
501​
5023. Use these two data packages in your application.
503​
504```tsx
505// Our application
506​
507import { ContainerDataProvider, useUser } from "@my-scope/container-data";
508import { AppDataProvider } from "@my-scope/app-data";
509import { MyComponentDataProvider, useItems } from "@my-scope/my-component-data";
510​
511<ContainerDataProvider> // <-- Provides container data (like "user") using its own React Query provider
512 ...
513 <AppDataProvider> // <-- Provides app data using its own React Query provider (unused in this example)
514 ...
515 <MyComponentDataProvider> // <-- Provides component data (like "items") using its own React Query provider
516 <MyComponent />
517 </MyComponentDataProvider>
518 ...
519 </AppDataProvider>
520 ...
521</ContainerDataProvider>
522​
523// Example of hooks provided by the "DataProvider" components above:
524const MyComponent = () => {
525 const user = useUser() // <-- Uses the context specified in ContainerDataProvider.
526 const items = useItems() // <-- Uses the context specified in MyComponentDataProvider
527 ...
529```