Open History to see the last commit
1---
2id: migrating-to-react-query-3
3title: Migrating to React Query 3
4---
5β
6Previous versions of React Query were awesome and brought some amazing new features, more magic, and an overall better experience to the library. They also brought on massive adoption and likewise a lot of refining fire (issues/contributions) to the library and brought to light a few things that needed more polish to make the library even better. v3 contains that very polish.
7β
8## Overview
9β
10- More scalable and testable cache configuration
11- Better SSR support
12- Data-lag (previously usePaginatedQuery) anywhere!
13- Bi-directional Infinite Queries
14- Query data selectors!
15- Fully configure defaults for queries and/or mutations before use
16- More granularity for optional rendering optimization
17- New `useQueries` hook! (Variable-length parallel query execution)
18- Query filter support for the `useIsFetching()` hook!
19- Retry/offline/replay support for mutations
20- Observe queries/mutations outside of React
21- Use the React Query core logic anywhere you want!
22- Bundled/Colocated Devtools via `react-query/devtools`
23- Cache Persistence to web storage (experimental via `react-query/persistQueryClient-experimental` and `react-query/createWebStoragePersistor-experimental`)
24β
25## Breaking Changes
26β
27### The `QueryCache` has been split into a `QueryClient` and lower-level `QueryCache` and `MutationCache` instances.
28β
29The `QueryCache` contains all queries, the `MutationCache` contains all mutations, and the `QueryClient` can be used to set configuration and to interact with them.
30β
31This has some benefits:
32β
33- Allows for different types of caches.
34- Multiple clients with different configurations can use the same cache.
35- Clients can be used to track queries, which can be used for shared caches on SSR.
36- The client API is more focused towards general usage.
37- Easier to test the individual components.
38β
39When creating a `new QueryClient()`, a `QueryCache` and `MutationCache` are automatically created for you if you don't supply them.
40β
41```tsx
42import { QueryClient } from 'react-query'
43β
44const queryClient = new QueryClient()
45```
46β
47### `ReactQueryConfigProvider` and `ReactQueryCacheProvider` have both been replaced by `QueryClientProvider`
48β
49Default options for queries and mutations can now be specified in `QueryClient`:
50β
51**Notice that it's now defaultOptions instead of defaultConfig**
52β
53```tsx
54const queryClient = new QueryClient({
55 defaultOptions: {
56 queries: {
57 // query options
58 },
59 mutations: {
60 // mutation options
61 },
62 },
63})
64```
65β
66The `QueryClientProvider` component is now used to connect a `QueryClient` to your application:
67β
68```tsx
69import { QueryClient, QueryClientProvider } from 'react-query'
70β
71const queryClient = new QueryClient()
72β
73function App() {
74 return <QueryClientProvider client={queryClient}>...</QueryClientProvider>
75}
76```
77β
78### The default `QueryCache` is gone. **For real this time!**
79β
80As previously noted with a deprecation, there is no longer a default `QueryCache` that is created or exported from the main package. **You must create your own via `new QueryClient()` or `new QueryCache()` (which you can then pass to `new QueryClient({ queryCache })` )**
81β
82### The deprecated `makeQueryCache` utility has been removed.
83β
84It's been a long time coming, but it's finally gone :)
85β
86### `QueryCache.prefetchQuery()` has been moved to `QueryClient.prefetchQuery()`
87β
88The new `QueryClient.prefetchQuery()` function is async, but **does not return the data from the query**. If you require the data, use the new `QueryClient.fetchQuery()` function
89β
90```tsx
91// Prefetch a query:
92await queryClient.prefetchQuery('posts', fetchPosts)
93β
94// Fetch a query:
95try {
96 const data = await queryClient.fetchQuery('posts', fetchPosts)
97} catch (error) {
98 // Error handling
99}
100```
101β
102### `ReactQueryErrorResetBoundary` and `QueryCache.resetErrorBoundaries()` have been replaced by `QueryErrorResetBoundary` and `useQueryErrorResetBoundary()`.
103β
104Together, these provide the same experience as before, but with added control to choose which component trees you want to reset. For more information, see:
105β
106- [QueryErrorResetBoundary](../reference/functions/QueryErrorResetBoundary.md)
107- [useQueryErrorResetBoundary](../reference/functions/useQueryErrorResetBoundary.md)
108β
109### `QueryCache.getQuery()` has been replaced by `QueryCache.find()`.
110β
111`QueryCache.find()` should now be used to look up individual queries from a cache
112β
113### `QueryCache.getQueries()` has been moved to `QueryCache.findAll()`.
114β
115`QueryCache.findAll()` should now be used to look up multiple queries from a cache
116β
117### `QueryCache.isFetching` has been moved to `QueryClient.isFetching()`.
118β
119**Notice that it's now a function instead of a property**
120β
121### The `useQueryCache` hook has been replaced by the `useQueryClient` hook.
122β
123It returns the provided `queryClient` for its component tree and shouldn't need much tweaking beyond a rename.
124β
125### Query key parts/pieces are no longer automatically spread to the query function.
126β
127Inline functions are now the suggested way of passing parameters to your query functions:
128β
129```tsx
130// Old
131useQuery(['post', id], (_key, id) => fetchPost(id))
132β
133// New
134useQuery(['post', id], () => fetchPost(id))
135```
136β
137If you still insist on not using inline functions, you can use the newly passed `QueryFunctionContext`:
138β
139```tsx
140useQuery(['post', id], (context) => fetchPost(context.queryKey[1]))
141```
142β
143### Infinite Query Page params are now passed via `QueryFunctionContext.pageParam`
144β
145They were previously added as the last query key parameter in your query function, but this proved to be difficult for some patterns
146β
147```tsx
148// Old
149useInfiniteQuery(['posts'], (_key, pageParam = 0) => fetchPosts(pageParam))
150β
151// New
152useInfiniteQuery(['posts'], ({ pageParam = 0 }) => fetchPosts(pageParam))
153```
154β
155### usePaginatedQuery() has been removed in favor of the `keepPreviousData` option
156β
157The new `keepPreviousData` options is available for both `useQuery` and `useInfiniteQuery` and will have the same "lagging" effect on your data:
158β
159```tsx
160import { useQuery } from 'react-query'
161β
162function Page({ page }) {
163 const { data } = useQuery(['page', page], fetchPage, {
164 keepPreviousData: true,
165 })
166}
167```
168β
169### useInfiniteQuery() is now bi-directional
170β
171The `useInfiniteQuery()` interface has changed to fully support bi-directional infinite lists.
172β
173- `options.getFetchMore` has been renamed to `options.getNextPageParam`
174- `queryResult.canFetchMore` has been renamed to `queryResult.hasNextPage`
175- `queryResult.fetchMore` has been renamed to `queryResult.fetchNextPage`
176- `queryResult.isFetchingMore` has been renamed to `queryResult.isFetchingNextPage`
177- Added the `options.getPreviousPageParam` option
178- Added the `queryResult.hasPreviousPage` property
179- Added the `queryResult.fetchPreviousPage` property
180- Added the `queryResult.isFetchingPreviousPage`
181- The `data` of an infinite query is now an object containing the `pages` and the `pageParams` used to fetch the pages: `{ pages: [data, data, data], pageParams: [...]}`
182β
183One direction:
184β
185```tsx
186const { data, fetchNextPage, hasNextPage, isFetchingNextPage } =
187 useInfiniteQuery(
188 'projects',
189 ({ pageParam = 0 }) => fetchProjects(pageParam),
190 {
191 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
192 },
193 )
194```
195β
196Both directions:
197β
198```tsx
199const {
200 data,
201 fetchNextPage,
202 fetchPreviousPage,
203 hasNextPage,
204 hasPreviousPage,
205 isFetchingNextPage,
206 isFetchingPreviousPage,
207} = useInfiniteQuery(
208 'projects',
209 ({ pageParam = 0 }) => fetchProjects(pageParam),
210 {
211 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
212 getPreviousPageParam: (firstPage, pages) => firstPage.prevCursor,
213 },
214)
215```
216β
217One direction reversed:
218β
219```tsx
220const { data, fetchNextPage, hasNextPage, isFetchingNextPage } =
221 useInfiniteQuery(
222 'projects',
223 ({ pageParam = 0 }) => fetchProjects(pageParam),
224 {
225 select: (data) => ({
226 pages: [...data.pages].reverse(),
227 pageParams: [...data.pageParams].reverse(),
228 }),
229 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
230 },
231 )
232```
233β
234### Infinite Query data now contains the array of pages and pageParams used to fetch those pages.
235β
236This allows for easier manipulation of the data and the page params, like, for example, removing the first page of data along with it's params:
237β
238```tsx
239queryClient.setQueryData(['projects'], (data) => ({
240 pages: data.pages.slice(1),
241 pageParams: data.pageParams.slice(1),
242}))
243```
244β
245### useMutation now returns an object instead of an array
246β
247Though the old way gave us warm fuzzy feelings of when we first discovered `useState` for the first time, they didn't last long. Now the mutation return is a single object.
248β
249```tsx
250// Old:
251const [mutate, { status, reset }] = useMutation()
252β
253// New:
254const { mutate, status, reset } = useMutation()
255```
256β
257### `mutation.mutate` no longer return a promise
258β
259- The `[mutate]` variable has been changed to the `mutation.mutate` function
260- Added the `mutation.mutateAsync` function
261β
262We got a lot of questions regarding this behavior as users expected the promise to behave like a regular promise.
263β
264Because of this the `mutate` function is now split into a `mutate` and `mutateAsync` function.
265β
266The `mutate` function can be used when using callbacks:
267β
268```tsx
269const { mutate } = useMutation({ mutationFn: addTodo })
270β
271mutate('todo', {
272 onSuccess: (data) => {
273 console.log(data)
274 },
275 onError: (error) => {
276 console.error(error)
277 },
278 onSettled: () => {
279 console.log('settled')
280 },
281})
282```
283β
284The `mutateAsync` function can be used when using async/await:
285β
286```tsx
287const { mutateAsync } = useMutation({ mutationFn: addTodo })
288β
289try {
290 const data = await mutateAsync('todo')
291 console.log(data)
292} catch (error) {
293 console.error(error)
294} finally {
295 console.log('settled')
296}
297```
298β
299### The object syntax for useQuery now uses a collapsed config:
300β
301```tsx
302// Old:
303useQuery({
304 queryKey: 'posts',
305 queryFn: fetchPosts,
306 config: { staleTime: Infinity },
307})
308β
309// New:
310useQuery({
311 queryKey: 'posts',
312 queryFn: fetchPosts,
313 staleTime: Infinity,
314})
315```
316β
317### If set, the QueryOptions.enabled option must be a boolean (`true`/`false`)
318β
319The `enabled` query option will now only disable a query when the value is `false`.
320If needed, values can be casted with `!!userId` or `Boolean(userId)` and a handy error will be thrown if a non-boolean value is passed.
321β
322### The QueryOptions.initialStale option has been removed
323β
324The `initialStale` query option has been removed and initial data is now treated as regular data.
325Which means that if `initialData` is provided, the query will refetch on mount by default.
326If you do not want to refetch immediately, you can define a `staleTime`.
327β
328### The `QueryOptions.forceFetchOnMount` option has been replaced by `refetchOnMount: 'always'`
329β
330Honestly, we were accruing way too many `refetchOn____` options, so this should clean things up.
331β
332### The `QueryOptions.refetchOnMount` options now only applies to its parent component instead of all query observers
333β
334When `refetchOnMount` was set to `false` any additional components were prevented from refetching on mount.
335In version 3 only the component where the option has been set will not refetch on mount.
336β
337### The `QueryOptions.queryFnParamsFilter` has been removed in favor of the new `QueryFunctionContext` object.
338β
339The `queryFnParamsFilter` option has been removed because query functions now get a `QueryFunctionContext` object instead of the query key.
340β
341Parameters can still be filtered within the query function itself as the `QueryFunctionContext` also contains the query key.
342β
343### The `QueryOptions.notifyOnStatusChange` option has been superseded by the new `notifyOnChangeProps` and `notifyOnChangePropsExclusions` options.
344β
345With these new options it is possible to configure when a component should re-render on a granular level.
346β
347Only re-render when the `data` or `error` properties change:
348β
349```tsx
350import { useQuery } from 'react-query'
351β
352function User() {
353 const { data } = useQuery(['user'], fetchUser, {
354 notifyOnChangeProps: ['data', 'error'],
355 })
356 return <div>Username: {data.username}</div>
357}
358```
359β
360Prevent re-render when the `isStale` property changes:
361β
362```tsx
363import { useQuery } from 'react-query'
364β
365function User() {
366 const { data } = useQuery(['user'], fetchUser, {
367 notifyOnChangePropsExclusions: ['isStale'],
368 })
369 return <div>Username: {data.username}</div>
370}
371```
372β
373### The `QueryResult.clear()` function has been renamed to `QueryResult.remove()`
374β
375Although it was called `clear`, it really just removed the query from the cache. The name now matches the functionality.
376β
377### The `QueryResult.updatedAt` property has been split into `QueryResult.dataUpdatedAt` and `QueryResult.errorUpdatedAt` properties
378β
379Because data and errors can be present at the same time, the `updatedAt` property has been split into `dataUpdatedAt` and `errorUpdatedAt`.
380β
381### `setConsole()` has been replaced by the new `setLogger()` function
382β
383```tsx
384import { setLogger } from 'react-query'
385β
386// Log with Sentry
387setLogger({
388 error: (error) => {
389 Sentry.captureException(error)
390 },
391})
392β
393// Log with Winston
394setLogger(winston.createLogger())
395```
396β
397### React Native no longer requires overriding the logger
398β
399To prevent showing error screens in React Native when a query fails it was necessary to manually change the Console:
400β
401```tsx
402import { setConsole } from 'react-query'
403β
404setConsole({
405 log: console.log,
406 warn: console.warn,
407 error: console.warn,
408})
409```
410β
411In version 3 **this is done automatically when React Query is used in React Native**.
412β
413### Typescript
414β
415#### `QueryStatus` has been changed from an [enum](https://www.typescriptlang.org/docs/handbook/enums.html#string-enums) to a [union type](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types)
416β
417So, if you were checking the status property of a query or mutation against a QueryStatus enum property you will have to check it now against the string literal the enum previously held for each property.
418β
419Therefore you have to change the enum properties to their equivalent string literal, like this:
420β
421- `QueryStatus.Idle` -> `'idle'`
422- `QueryStatus.Loading` -> `'loading'`
423- `QueryStatus.Error` -> `'error'`
424- `QueryStatus.Success` -> `'success'`
425β
426Here is an example of the changes you would have to make:
427β
428```tsx
429- import { useQuery, QueryStatus } from 'react-query'; // [!code --]
430+ import { useQuery } from 'react-query'; // [!code ++]
431β
432const { data, status } = useQuery(['post', id], () => fetchPost(id))
433β
434- if (status === QueryStatus.Loading) { // [!code --]
435+ if (status === 'loading') { // [!code ++]
436 ...
437}
438β
439- if (status === QueryStatus.Error) { // [!code --]
440+ if (status === 'error') { // [!code ++]
441 ...
442}
443```
444β
445## New features
446β
447#### Query Data Selectors
448β
449The `useQuery` and `useInfiniteQuery` hooks now have a `select` option to select or transform parts of the query result.
450β
451```tsx
452import { useQuery } from 'react-query'
453β
454function User() {
455 const { data } = useQuery(['user'], fetchUser, {
456 select: (user) => user.username,
457 })
458 return <div>Username: {data}</div>
459}
460```
461β
462Set the `notifyOnChangeProps` option to `['data', 'error']` to only re-render when the selected data changes.
463β
464#### The useQueries() hook, for variable-length parallel query execution
465β
466Wish you could run `useQuery` in a loop? The rules of hooks say no, but with the new `useQueries()` hook, you can!
467β
468```tsx
469import { useQueries } from 'react-query'
470β
471function Overview() {
472 const results = useQueries([
473 { queryKey: ['post', 1], queryFn: fetchPost },
474 { queryKey: ['post', 2], queryFn: fetchPost },
475 ])
476 return (
477 <ul>
478 {results.map(({ data }) => data && <li key={data.id}>{data.title})</li>)}
479 </ul>
480 )
481}
482```
483β
484#### Retry/offline mutations
485β
486By default React Query will not retry a mutation on error, but it is possible with the `retry` option:
487β
488```tsx
489const mutation = useMutation({
490 mutationFn: addTodo,
491 retry: 3,
492})
493```
494β
495If mutations fail because the device is offline, they will be retried in the same order when the device reconnects.
496β
497#### Persist mutations
498β
499Mutations can now be persisted to storage and resumed at a later point. More information can be found in the mutations documentation.
500β
501#### QueryObserver
502β
503A `QueryObserver` can be used to create and/or watch a query:
504β
505```tsx
506const observer = new QueryObserver(queryClient, { queryKey: 'posts' })
507β
508const unsubscribe = observer.subscribe((result) => {
509 console.log(result)
510 unsubscribe()
511})
512```
513β
514#### InfiniteQueryObserver
515β
516A `InfiniteQueryObserver` can be used to create and/or watch an infinite query:
517β
518```tsx
519const observer = new InfiniteQueryObserver(queryClient, {
520 queryKey: 'posts',
521 queryFn: fetchPosts,
522 getNextPageParam: (lastPage, allPages) => lastPage.nextCursor,
523 getPreviousPageParam: (firstPage, allPages) => firstPage.prevCursor,
524})
525β
526const unsubscribe = observer.subscribe((result) => {
527 console.log(result)
528 unsubscribe()
529})
530```
531β
532#### QueriesObserver
533β
534A `QueriesObserver` can be used to create and/or watch multiple queries:
535β
536```tsx
537const observer = new QueriesObserver(queryClient, [
538 { queryKey: ['post', 1], queryFn: fetchPost },
539 { queryKey: ['post', 2], queryFn: fetchPost },
540])
541β
542const unsubscribe = observer.subscribe((result) => {
543 console.log(result)
544 unsubscribe()
545})
546```
547β
548#### Set default options for specific queries
549β
550The `QueryClient.setQueryDefaults()` method can be used to set default options for specific queries:
551β
552```tsx
553queryClient.setQueryDefaults(['posts'], { queryFn: fetchPosts })
554β
555function Component() {
556 const { data } = useQuery(['posts'])
557}
558```
559β
560#### Set default options for specific mutations
561β
562The `QueryClient.setMutationDefaults()` method can be used to set default options for specific mutations:
563β
564```tsx
565queryClient.setMutationDefaults(['addPost'], { mutationFn: addPost })
566β
567function Component() {
568 const { mutate } = useMutation({ mutationKey: ['addPost'] })
569}
570```
571β
572#### useIsFetching()
573β
574The `useIsFetching()` hook now accepts filters which can be used to for example only show a spinner for certain type of queries:
575β
576```tsx
577const fetches = useIsFetching({ queryKey: ['posts'] })
578```
579β
580#### Core separation
581β
582The core of React Query is now fully separated from React, which means it can also be used standalone or in other frameworks. Use the `react-query/core` entry point to only import the core functionality:
583β
584```tsx
585import { QueryClient } from 'react-query/core'
586```
587β
588### Devtools are now part of the main repo and npm package
589β
590The devtools are now included in the `react-query` package itself under the import `react-query/devtools`. Simply replace `react-query-devtools` imports with `react-query/devtools`