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

migrating-to-react-query-3.md

590 lines18.2 KB

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>
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
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.md)
107- [useQueryErrorResetBoundary](../../reference/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 })
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 },
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')
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>
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>
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 ...
438​
439- if (status === QueryStatus.Error) { // [!code --]
440+ if (status === 'error') { // [!code ++]
441 ...
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>
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 )
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'])
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'] })
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`