Open History to see the last commit
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```diff
21- import { useQuery } from 'react-query'
22- import { ReactQueryDevtools } from 'react-query/devtools'
23β
24+ import { useQuery } from '@tanstack/react-query'
25+ import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
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](../guides/default-query-function) easier.
62β
63However, we have not followed this concept through to all apis. For example, when using the `predicate` function on [Query Filters](../guides/filters) 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```diff
68- useQuery('todos', fetchTodos)
69+ useQuery(['todos'], fetchTodos)
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](../guides/queries#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](../guides/queries#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```diff
108- status: 'idle'
109+ status: 'loading'
110+ fetchStatus: 'idle'
111```
112β
113Also, have a look at [the guide on dependent queries](../guides/dependent-queries)
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```diff
120- isLoading
121+ isInitialLoading
122```
123β
124See also the guide on [disabling queries](../guides/disabling-queries#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```diff
131- useQueries([{ queryKey1, queryFn1, options1 }, { queryKey2, queryFn2, options2 }])
132+ useQueries({ queries: [{ queryKey1, queryFn1, options1 }, { queryKey2, queryFn2, options2 }] })
133```
134β
135### Undefined is an illegal cache value for successful queries
136β
137In 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](guides/initial-query-data#initial-data-function) will also _not_ set data.
138β
139Further, it is an easy bug to produce `Promise<void>` by adding logging in the queryFn:
140β
141```tsx
142useQuery(['key'], () =>
143 axios.get(url).then((result) => console.log(result.data)),
144)
145```
146β
147This 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.
148β
149### Queries and mutations, per default, need network connection to run
150β
151Please read the [New Features announcement](#proper-offline-support) about online / offline support, and also the dedicated page about [Network mode](../guides/network-mode)
152β
153Even 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:
154β
155```tsx
156new QueryClient({
157 defaultOptions: {
158 queries: {
159 networkMode: 'offlineFirst',
160 },
161 mutations: {
162 networkMode: 'offlineFirst',
163 },
164 },
165})
166```
167β
168### `notifyOnChangeProps` property no longer accepts `"tracked"` as a value
169β
170The `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.
171β
172If 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.
173β
174### `notifyOnChangePropsExclusion` has been removed
175β
176In 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.
177β
178### Consistent behavior for `cancelRefetch`
179β
180The `cancelRefetch` option can be passed to all functions that imperatively fetch a query, namely:
181β
182- `queryClient.refetchQueries`
183- `queryClient.invalidateQueries`
184- `queryClient.resetQueries`
185- `refetch` returned from `useQuery`
186- `fetchNextPage` and `fetchPreviousPage` returned from `useInfiniteQuery`
187β
188Except 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.
189β
190We believe that if a query is actively refetched by some code you write, it should, per default, re-start the fetch.
191β
192That 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:
193β
194```
195queryClient.refetchQueries({ queryKey: ['todos'] })
196// this will abort the previous refetch and start a new fetch
197queryClient.refetchQueries({ queryKey: ['todos'] })
198```
199β
200You can opt-out of this behaviour by explicitly passing `cancelRefetch:false`:
201β
202```
203queryClient.refetchQueries({ queryKey: ['todos'] })
204// this will not abort the previous refetch - it will just be ignored
205queryClient.refetchQueries({ queryKey: ['todos'] }, { cancelRefetch: false })
206```
207β
208> Note: There is no change in behaviour for automatically triggered fetches, e.g. because a query mounts or because of a window focus refetch.
209β
210### Query Filters
211β
212A [query filter](../guides/filters) 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:
213β
214```
215active?: boolean
216 - When set to true it will match active queries.
217 - When set to false it will match inactive queries.
218inactive?: boolean
219 - When set to true it will match inactive queries.
220 - When set to false it will match active queries.
221```
222β
223Those 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.
224β
225With v4, those filters have been combined into a single filter to better show the intent:
226β
227```diff
228- active?: boolean
229- inactive?: boolean
230+ type?: 'active' | 'inactive' | 'all'
231```
232β
233The filter defaults to `all`, and you can choose to only match `active` or `inactive` queries.
234β
235#### refetchActive / refetchInactive
236β
237[queryClient.invalidateQueries](../reference/QueryClient#queryclientinvalidatequeries) had two additional, similar flags:
238β
239```
240refetchActive: Boolean
241 - Defaults to true
242 - When set to false, queries that match the refetch predicate and are actively being rendered
243 via useQuery and friends will NOT be refetched in the background, and only marked as invalid.
244refetchInactive: Boolean
245 - Defaults to false
246 - When set to true, queries that match the refetch predicate and are not being rendered
247 via useQuery and friends will be both marked as invalid and also refetched in the background
248```
249β
250For the same reason, those have also been combined:
251β
252```diff
253- refetchActive?: boolean
254- refetchInactive?: boolean
255+ refetchType?: 'active' | 'inactive' | 'all' | 'none'
256```
257β
258This 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.
259β
260### `onSuccess` is no longer called from `setQueryData`
261β
262This 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.
263β
264Similar to `onError` and `onSettled`, the `onSuccess` callback is now tied to a request being made. No request -> no callback.
265β
266If 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:
267β
268```
269const { data } = useQuery({ queryKey, queryFn })
270React.useEffect(() => mySideEffectHere(data), [data])
271```
272β
273### `persistQueryClient` and the corresponding persister plugins are no longer experimental and have been renamed
274β
275The plugins `createWebStoragePersistor` and `createAsyncStoragePersistor` have been renamed to [`createSyncStoragePersister`](../plugins/createSyncStoragePersister) and [`createAsyncStoragePersister`](../plugins/createAsyncStoragePersister) 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.
276β
277Since these plugins are no longer experimental, their import paths have also been updated:
278β
279```diff
280- import { persistQueryClient } from 'react-query/persistQueryClient-experimental'
281- import { createWebStoragePersistor } from 'react-query/createWebStoragePersistor-experimental'
282- import { createAsyncStoragePersistor } from 'react-query/createAsyncStoragePersistor-experimental'
283β
284+ import { persistQueryClient } from '@tanstack/react-query-persist-client'
285+ import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'
286+ import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister'
287```
288β
289### The `cancel` method on promises is no longer supported
290β
291The [old `cancel` method](../guides/query-cancellation#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](../guides/query-cancellation) (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.
292β
293### TypeScript
294β
295Types now require using TypeScript v4.1 or greater
296β
297### Supported Browsers
298β
299As 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).
300β
301### `setLogger` is removed
302β
303It was possible to change the logger globally by calling `setLogger`. In v4, that function is replaced with an optional field when creating a `QueryClient`.
304β
305```diff
306- import { QueryClient, setLogger } from 'react-query';
307+ import { QueryClient } from '@tanstack/react-query';
308β
309- setLogger(customLogger)
310- const queryClient = new QueryClient();
311+ const queryClient = new QueryClient({ logger: customLogger })
312```
313β
314### No _default_ manual Garbage Collection server-side
315β
316In 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.
317β
318This 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).
319β
320This 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).
321β
322### Logging in production
323β
324Starting 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.
325Errors will still show up in development mode.
326β
327### ESM Support
328β
329React 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.
330β
331### Streamlined NotifyEvents
332β
333Subscribing 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.
334β
335#### QueryCacheNotifyEvent
336β
337```diff
338- type: 'queryAdded'
339+ type: 'added'
340- type: 'queryRemoved'
341+ type: 'removed'
342- type: 'queryUpdated'
343+ type: 'updated'
344```
345β
346#### MutationCacheNotifyEvent
347β
348The `MutationCacheNotifyEvent` uses the same types as the `QueryCacheNotifyEvent`.
349β
350> Note: This is only relevant if you manually subscribe to the caches via `queryCache.subscribe` or `mutationCache.subscribe`
351β
352### Separate hydration exports have been removed
353β
354With 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.
355β
356```diff
357- import { dehydrate, hydrate, useHydrate, Hydrate } from 'react-query/hydration'
358+ import { dehydrate, hydrate, useHydrate, Hydrate } from '@tanstack/react-query'
359```
360β
361### Removed undocumented methods from the `queryClient`, `query` and `mutation`
362β
363The methods `cancelMutatations` 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`
364β
365```diff
366- executeMutation<
367- TData = unknown,
368- TError = unknown,
369- TVariables = void,
370- TContext = unknown
371- >(
372- options: MutationOptions<TData, TError, TVariables, TContext>
373- ): Promise<TData> {
374- return this.mutationCache.build(this, options).execute()
375- }
376```
377β
378Additionally, `query.setDefaultOptions` was removed because it was also unused. `mutation.cancel` was removed because it didn't actually cancel the outgoing request.
379β
380### The `src/react` directory was renamed to `src/reactjs`
381β
382Previously, 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:
383β
384```
385TypeError: Cannot read property 'createContext' of undefined
386```
387β
388With the renamed directory this no longer is an issue.
389β
390If 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:
391β
392```diff
393- import { QueryClientProvider } from 'react-query/react';
394+ import { QueryClientProvider } from '@tanstack/react-query/reactjs';
395```
396β
397## New Features π
398β
399v4 comes with an awesome set of new features:
400β
401### Support for React 18
402β
403React 18 was released earlier this year, and v4 now has first class support for it and the new concurrent features it brings.
404β
405### Proper offline support
406β
407In 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:
408β
409- 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.
410- Similarly, if you are offline and have retries turned off, your query will just fire and fail, and the query goes to error state.
411- 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.
412- Window focus refetching didn't do anything at all if you were offline.
413β
414With v4, React Query introduces a new `networkMode` to tackle all these issues. Please read the dedicated page about the new [Network mode](../guides/network-mode) for more information.
415β
416### Tracked Queries per default
417β
418React 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.
419β
420### Bailing out of updates with setQueryData
421β
422When using the [functional updater form of setQueryData](../reference/QueryClient#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:
423β
424```tsx
425queryClient.setQueryData(['todo', id], (previousTodo) =>
426 previousTodo ? { ...previousTodo, done: true } : undefined,
427)
428```
429β
430### Mutation Cache Garbage Collection
431β
432Mutations can now also be garbage collected automatically, just like queries. The default `cacheTime` for mutations is also set to 5 minutes.
433β
434### Custom Contexts for Multiple Providers
435β
436Custom 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.
437β
438An example:
439β
4401. Create a data package.
441β
442```tsx
443// Our first data package: @my-scope/container-data
444β
445const context = React.createContext<QueryClient | undefined>(undefined)
446const queryClient = new QueryClient()
447β
448export const useUser = () => {
449 return useQuery(USER_KEY, USER_FETCHER, {
450 context,
451 })
452}
453β
454export const ContainerDataProvider = ({
455 children,
456}: {
457 children: React.ReactNode
458}) => {
459 return (
460 <QueryClientProvider client={queryClient} context={context}>
461 {children}
462 </QueryClientProvider>
463 )
464}
465```
466β
4672. Create a second data package.
468β
469```tsx
470// Our second data package: @my-scope/my-component-data
471β
472const context = React.createContext<QueryClient | undefined>(undefined)
473const queryClient = new QueryClient()
474β
475export const useItems = () => {
476 return useQuery(ITEMS_KEY, ITEMS_FETCHER, {
477 context,
478 })
479}
480β
481export const MyComponentDataProvider = ({
482 children,
483}: {
484 children: React.ReactNode
485}) => {
486 return (
487 <QueryClientProvider client={queryClient} context={context}>
488 {children}
489 </QueryClientProvider>
490 )
491}
492```
493β
4943. Use these two data packages in your application.
495β
496```tsx
497// Our application
498β
499import { ContainerDataProvider, useUser } from "@my-scope/container-data";
500import { AppDataProvider } from "@my-scope/app-data";
501import { MyComponentDataProvider, useItems } from "@my-scope/my-component-data";
502β
503<ContainerDataProvider> // <-- Provides container data (like "user") using its own React Query provider
504 ...
505 <AppDataProvider> // <-- Provides app data using its own React Query provider (unused in this example)
506 ...
507 <MyComponentDataProvider> // <-- Provides component data (like "items") using its own React Query provider
508 <MyComponent />
509 </MyComponentDataProvider>
510 ...
511 </AppDataProvider>
512 ...
513</ContainerDataProvider>
514β
515// Example of hooks provided by the "DataProvider" components above:
516const MyComponent = () => {
517 const user = useUser() // <-- Uses the context specified in ContainerDataProvider.
518 const items = useItems() // <-- Uses the context specified in MyComponentDataProvider
519 ...
520}
521```