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/QueryErrorResetBoundary)
107- [useQueryErrorResetBoundary](../reference/useQueryErrorResetBoundary)
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 {
187 data,
188 fetchNextPage,
189 hasNextPage,
190 isFetchingNextPage,
191} = useInfiniteQuery(
192 'projects',
193 ({ pageParam = 0 }) => fetchProjects(pageParam),
194 {
195 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
196 }
197)
198```
199β
200Both directions:
201β
202```tsx
203const {
204 data,
205 fetchNextPage,
206 fetchPreviousPage,
207 hasNextPage,
208 hasPreviousPage,
209 isFetchingNextPage,
210 isFetchingPreviousPage,
211} = useInfiniteQuery(
212 'projects',
213 ({ pageParam = 0 }) => fetchProjects(pageParam),
214 {
215 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
216 getPreviousPageParam: (firstPage, pages) => firstPage.prevCursor,
217 }
218)
219```
220β
221One direction reversed:
222β
223```tsx
224const {
225 data,
226 fetchNextPage,
227 hasNextPage,
228 isFetchingNextPage,
229} = useInfiniteQuery(
230 'projects',
231 ({ pageParam = 0 }) => fetchProjects(pageParam),
232 {
233 select: data => ({
234 pages: [...data.pages].reverse(),
235 pageParams: [...data.pageParams].reverse(),
236 }),
237 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
238 }
239)
240```
241β
242### Infinite Query data now contains the array of pages and pageParams used to fetch those pages.
243β
244This 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:
245β
246```tsx
247queryClient.setQueryData(['projects'], data => ({
248 pages: data.pages.slice(1),
249 pageParams: data.pageParams.slice(1),
250}))
251```
252β
253### useMutation now returns an object instead of an array
254β
255Though 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.
256β
257```tsx
258// Old:
259const [mutate, { status, reset }] = useMutation()
260β
261// New:
262const { mutate, status, reset } = useMutation()
263```
264β
265### `mutation.mutate` no longer return a promise
266β
267- The `[mutate]` variable has been changed to the `mutation.mutate` function
268- Added the `mutation.mutateAsync` function
269β
270We got a lot of questions regarding this behavior as users expected the promise to behave like a regular promise.
271β
272Because of this the `mutate` function is now split into a `mutate` and `mutateAsync` function.
273β
274The `mutate` function can be used when using callbacks:
275β
276```tsx
277const { mutate } = useMutation({ mutationFn: addTodo })
278β
279mutate('todo', {
280 onSuccess: data => {
281 console.log(data)
282 },
283 onError: error => {
284 console.error(error)
285 },
286 onSettled: () => {
287 console.log('settled')
288 },
289})
290```
291β
292The `mutateAsync` function can be used when using async/await:
293β
294```tsx
295const { mutateAsync } = useMutation({ mutationFn: addTodo })
296β
297try {
298 const data = await mutateAsync('todo')
299 console.log(data)
300} catch (error) {
301 console.error(error)
302} finally {
303 console.log('settled')
304}
305```
306β
307### The object syntax for useQuery now uses a collapsed config:
308β
309```tsx
310// Old:
311useQuery({
312 queryKey: 'posts',
313 queryFn: fetchPosts,
314 config: { staleTime: Infinity },
315})
316β
317// New:
318useQuery({
319 queryKey: 'posts',
320 queryFn: fetchPosts,
321 staleTime: Infinity,
322})
323```
324β
325### If set, the QueryOptions.enabled option must be a boolean (`true`/`false`)
326β
327The `enabled` query option will now only disable a query when the value is `false`.
328If needed, values can be casted with `!!userId` or `Boolean(userId)` and a handy error will be thrown if a non-boolean value is passed.
329β
330### The QueryOptions.initialStale option has been removed
331β
332The `initialStale` query option has been removed and initial data is now treated as regular data.
333Which means that if `initialData` is provided, the query will refetch on mount by default.
334If you do not want to refetch immediately, you can define a `staleTime`.
335β
336### The `QueryOptions.forceFetchOnMount` option has been replaced by `refetchOnMount: 'always'`
337β
338Honestly, we were accruing way too many `refetchOn____` options, so this should clean things up.
339β
340### The `QueryOptions.refetchOnMount` options now only applies to its parent component instead of all query observers
341β
342When `refetchOnMount` was set to `false` any additional components were prevented from refetching on mount.
343In version 3 only the component where the option has been set will not refetch on mount.
344β
345### The `QueryOptions.queryFnParamsFilter` has been removed in favor of the new `QueryFunctionContext` object.
346β
347The `queryFnParamsFilter` option has been removed because query functions now get a `QueryFunctionContext` object instead of the query key.
348β
349Parameters can still be filtered within the query function itself as the `QueryFunctionContext` also contains the query key.
350β
351### The `QueryOptions.notifyOnStatusChange` option has been superseded by the new `notifyOnChangeProps` and `notifyOnChangePropsExclusions` options.
352β
353With these new options it is possible to configure when a component should re-render on a granular level.
354β
355Only re-render when the `data` or `error` properties change:
356β
357```tsx
358import { useQuery } from 'react-query'
359β
360function User() {
361 const { data } = useQuery(['user'], fetchUser, {
362 notifyOnChangeProps: ['data', 'error'],
363 })
364 return <div>Username: {data.username}</div>
365}
366```
367β
368Prevent re-render when the `isStale` property changes:
369β
370```tsx
371import { useQuery } from 'react-query'
372β
373function User() {
374 const { data } = useQuery(['user'], fetchUser, {
375 notifyOnChangePropsExclusions: ['isStale'],
376 })
377 return <div>Username: {data.username}</div>
378}
379```
380β
381### The `QueryResult.clear()` function has been renamed to `QueryResult.remove()`
382β
383Although it was called `clear`, it really just removed the query from the cache. The name now matches the functionality.
384β
385### The `QueryResult.updatedAt` property has been split into `QueryResult.dataUpdatedAt` and `QueryResult.errorUpdatedAt` properties
386β
387Because data and errors can be present at the same time, the `updatedAt` property has been split into `dataUpdatedAt` and `errorUpdatedAt`.
388β
389### `setConsole()` has been replaced by the new `setLogger()` function
390β
391```tsx
392import { setLogger } from 'react-query'
393β
394// Log with Sentry
395setLogger({
396 error: error => {
397 Sentry.captureException(error)
398 },
399})
400β
401// Log with Winston
402setLogger(winston.createLogger())
403```
404β
405### React Native no longer requires overriding the logger
406β
407To prevent showing error screens in React Native when a query fails it was necessary to manually change the Console:
408β
409```tsx
410import { setConsole } from 'react-query'
411β
412setConsole({
413 log: console.log,
414 warn: console.warn,
415 error: console.warn,
416})
417```
418β
419In version 3 **this is done automatically when React Query is used in React Native**.
420β
421β
422### Typescript
423#### `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)
424β
425So, 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.
426β
427Therefore you have to change the enum properties to their equivalent string literal, like this:
428- `QueryStatus.Idle` -> `'idle'`
429- `QueryStatus.Loading` -> `'loading'`
430- `QueryStatus.Error` -> `'error'`
431- `QueryStatus.Success` -> `'success'`
432β
433Here is an example of the changes you would have to make:
434β
435```diff
436- import { useQuery, QueryStatus } from 'react-query';
437+ import { useQuery } from 'react-query';
438β
439const { data, status } = useQuery(['post', id], () => fetchPost(id))
440β
441- if (status === QueryStatus.Loading) {
442+ if (status === 'loading') {
443 ...
444}
445β
446- if (status === QueryStatus.Error) {
447+ if (status === 'error') {
448 ...
449}
450```
451β
452## New features
453β
454#### Query Data Selectors
455β
456The `useQuery` and `useInfiniteQuery` hooks now have a `select` option to select or transform parts of the query result.
457β
458```tsx
459import { useQuery } from 'react-query'
460β
461function User() {
462 const { data } = useQuery(['user'], fetchUser, {
463 select: user => user.username,
464 })
465 return <div>Username: {data}</div>
466}
467```
468β
469Set the `notifyOnChangeProps` option to `['data', 'error']` to only re-render when the selected data changes.
470β
471#### The useQueries() hook, for variable-length parallel query execution
472β
473Wish you could run `useQuery` in a loop? The rules of hooks say no, but with the new `useQueries()` hook, you can!
474β
475```tsx
476import { useQueries } from 'react-query'
477β
478function Overview() {
479 const results = useQueries([
480 { queryKey: ['post', 1], queryFn: fetchPost },
481 { queryKey: ['post', 2], queryFn: fetchPost },
482 ])
483 return (
484 <ul>
485 {results.map(({ data }) => data && <li key={data.id}>{data.title})</li>)}
486 </ul>
487 )
488}
489```
490β
491#### Retry/offline mutations
492β
493By default React Query will not retry a mutation on error, but it is possible with the `retry` option:
494β
495```tsx
496const mutation = useMutation({
497 mutationFn: addTodo,
498 retry: 3,
499})
500```
501β
502If mutations fail because the device is offline, they will be retried in the same order when the device reconnects.
503β
504#### Persist mutations
505β
506Mutations can now be persisted to storage and resumed at a later point. More information can be found in the mutations documentation.
507β
508#### QueryObserver
509β
510A `QueryObserver` can be used to create and/or watch a query:
511β
512```tsx
513const observer = new QueryObserver(queryClient, { queryKey: 'posts' })
514β
515const unsubscribe = observer.subscribe(result => {
516 console.log(result)
517 unsubscribe()
518})
519```
520β
521#### InfiniteQueryObserver
522β
523A `InfiniteQueryObserver` can be used to create and/or watch an infinite query:
524β
525```tsx
526const observer = new InfiniteQueryObserver(queryClient, {
527 queryKey: 'posts',
528 queryFn: fetchPosts,
529 getNextPageParam: (lastPage, allPages) => lastPage.nextCursor,
530 getPreviousPageParam: (firstPage, allPages) => firstPage.prevCursor,
531})
532β
533const unsubscribe = observer.subscribe(result => {
534 console.log(result)
535 unsubscribe()
536})
537```
538β
539#### QueriesObserver
540β
541A `QueriesObserver` can be used to create and/or watch multiple queries:
542β
543```tsx
544const observer = new QueriesObserver(queryClient, [
545 { queryKey: ['post', 1], queryFn: fetchPost },
546 { queryKey: ['post', 2], queryFn: fetchPost },
547])
548β
549const unsubscribe = observer.subscribe(result => {
550 console.log(result)
551 unsubscribe()
552})
553```
554β
555#### Set default options for specific queries
556β
557The `QueryClient.setQueryDefaults()` method can be used to set default options for specific queries:
558β
559```tsx
560queryClient.setQueryDefaults(['posts'], { queryFn: fetchPosts })
561β
562function Component() {
563 const { data } = useQuery(['posts'])
564}
565```
566β
567#### Set default options for specific mutations
568β
569The `QueryClient.setMutationDefaults()` method can be used to set default options for specific mutations:
570β
571```tsx
572queryClient.setMutationDefaults(['addPost'], { mutationFn: addPost })
573β
574function Component() {
575 const { mutate } = useMutation({ mutationKey: ['addPost'] })
576}
577```
578β
579#### useIsFetching()
580β
581The `useIsFetching()` hook now accepts filters which can be used to for example only show a spinner for certain type of queries:
582β
583```tsx
584const fetches = useIsFetching({ queryKey: ['posts'] })
585```
586β
587#### Core separation
588β
589The 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:
590β
591```tsx
592import { QueryClient } from 'react-query/core'
593```
594β
595### Devtools are now part of the main repo and npm package
596β
597The 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`