Open History to see the last commit
1
2
3<img src='https://github.com/tannerlinsley/react-query/raw/master/media/logo.png' width='300'/>
4
5Hooks for fetching, caching and updating asynchronous data in React
6
7<!-- <a href="https://travis-ci.org/tannerlinsley/react-query" target="\_parent">
8 <img alt="" src="https://travis-ci.org/tannerlinsley/react-query.svg?branch=master" />
9</a> -->
10<a href="https://npmjs.com/package/react-query" target="\_parent">
11 <img alt="" src="https://img.shields.io/npm/dm/react-query.svg" />
12</a>
13<a href="https://bundlephobia.com/result?p=react-query@latest" target="\_parent">
14 <img alt="" src="https://badgen.net/bundlephobia/minzip/react-query@latest" />
15</a>
16<a href="https://spectrum.chat/react-query">
17 <img alt="Join the community on Spectrum" src="https://withspectrum.github.io/badge/badge.svg" />
18</a>
19<a href="https://github.com/tannerlinsley/react-query" target="\_parent">
20 <img alt="" src="https://img.shields.io/github/stars/tannerlinsley/react-query.svg?style=social&label=Star" />
21</a>
22<a href="https://twitter.com/tannerlinsley" target="\_parent">
23 <img alt="" src="https://img.shields.io/twitter/follow/tannerlinsley.svg?style=social&label=Follow" />
24</a>
25
26## Quick Features
27
28- Transport, protocol & backend agnostic data fetching
29- Auto Caching + Refetching (stale-while-revalidate, Window Refocus, Polling/Realtime)
30- Parallel + Dependent Queries
31- Mutations + Automatic Query Refetching
32- Multi-layer Cache + Garbage Collection
33- Load-More Pagination + Scroll Recovery
34- [React Suspense](https://reactjs.org/docs/concurrent-mode-suspense.html) Support
35- <a href="https://bundlephobia.com/result?p=react-query@latest" target="\_parent">
36 <img alt="" src="https://badgen.net/bundlephobia/minzip/react-query@latest" />
37 </a>
38
39<details>
40<summary>Core Issues and Solution</summary>
41
42## The Challenge
43
44Tools for managing async data and client stores/caches are plentiful these days, but most of these tools:
45
46- Duplicate unnecessary network operations
47- Force normalized or object/id-based caching strategies on your data
48- Do not automatically manage stale-ness or caching
49- Do not offer robust API's around mutation events, invalidation or query management
50- Are built for highly-opinionated systems like Redux, GraphQL, [insert proprietary tools] etc.
51
52## The Solution
53
54React Query exports a set of hooks that attempt to address these issues. Out of the box, React Query:
55
56- Flexibly dedupes simultaneous requests to assets
57- Automatically caches data
58- Automatically invalidates stale cache data
59- Optimistically updates stale requests in the background
60- Automatically manages garbage collection
61- Supports automatic retries and exponential or custom back-off delays
62- Provides both declarative and imperative API's for:
63 - Mutations and automatic query syncing
64 - Query Refetching
65 - Atomic and Optimistic query manipulation
66
67</details>
68
69<details>
70<summary>Inspiration & Hat-Tipping</summary>
71<br />
72A big thanks to both [Draqula](https://github.com/vadimdemedes/draqula) for inspiring a lot of React Query's original API and documentation and also [Zeit's SWR](https://github.com/zeit/swr) and its creators for inspiring even further customizations and examples. You all rock!
73
74</details>
75
76## Examples
77
78- [Basic](./examples/basic)
79- [Custom Hooks](./examples/custom-hooks)
80- [Auto Refetching / Polling / Realtime](./examples/auto-refetching)
81- [Window Refocus Refetching](./examples/focus-refetching)
82- [Optimistic Updates](./examples/optimistic-updates)
83- [Load-More Pagination](./examples/load-more-pagination)
84- [Suspense CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-query/tree/master/examples/suspense)
85- [Playground CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-query/tree/master/examples/sandbox)
86
87## Sponsors
88
89This library is being built and maintained by me, @tannerlinsley and I am always in need of more support to keep projects like this afloat. If you would like to get premium support, add your logo or name on this README, or simply just contribute to my open source Sponsorship goal, [visit my Github Sponsors page!](https://github.com/sponsors/tannerlinsley/)
90
91<table>
92 <tbody>
93 <tr>
94 <td align="center" valign="middle">
95 <a href="https://github.com/sponsors/tannerlinsley" target="_blank">
96 <img width='150' src="https://raw.githubusercontent.com/tannerlinsley/files/master/images/patreon/diamond.png">
97 </a>
98 </td>
99 <td align="center" valign="middle">
100 <a href="https://github.com/sponsors/tannerlinsley" target="_blank">
101 Become a Sponsor!
102 </a>
103 </td>
104 </tr>
105 </tbody>
106</table>
107
108<table>
109 <tbody>
110 <tr>
111 <td align="center" valign="middle">
112 <a href="https://github.com/sponsors/tannerlinsley/" target="_blank">
113 <img width='150' src="https://raw.githubusercontent.com/tannerlinsley/files/master/images/patreon/platinum.png">
114 </a>
115 </td>
116 <td align="center" valign="middle">
117 <a href="https://github.com/sponsors/tannerlinsley" target="_blank">
118 Become a Sponsor!
119 </a>
120 </td>
121 </tr>
122 </tbody>
123</table>
124
125<table>
126 <tbody>
127 <tr>
128 <td align="center" valign="middle">
129 <a href="https://github.com/sponsors/tannerlinsley/" target="_blank">
130 <img width='150' src="https://raw.githubusercontent.com/tannerlinsley/files/master/images/patreon/gold.png">
131 </a>
132 </td>
133 <td align="center" valign="middle">
134 <a href="https://github.com/sponsors/tannerlinsley" target="_blank">
135 Become a Sponsor!
136 </a>
137 </td>
138 </tr>
139 </tbody>
140</table>
141
142<table>
143 <tbody>
144 <tr>
145 <td align="center" valign="middle">
146 <a href="https://github.com/sponsors/tannerlinsley/" target="_blank">
147 <img width='150' src="https://raw.githubusercontent.com/tannerlinsley/files/master/images/patreon/silver.png">
148 </a>
149 </td>
150 <td align="center" valign="middle">
151 <a href="https://github.com/sponsors/tannerlinsley" target="_blank">
152 Become a Sponsor!
153 </a>
154 </td>
155 </tr>
156 </tbody>
157</table>
158
159<table>
160 <tbody>
161 <tr>
162 <td valign="top">
163 <a href="https://github.com/sponsors/tannerlinsley/">
164 <img width='150' src="https://raw.githubusercontent.com/tannerlinsley/files/master/images/patreon/supporters.png" />
165 </a>
166 </td>
167 <!-- <td>
168 <ul>
169 <li><a href=""><a></li>
170 </ul>
171 </td> -->
172 <td>
173 <a href="https://github.com/sponsors/tannerlinsley" target="_blank">
174 Become a Supporter!
175 </a>
176 </td>
177 </tr>
178 </tbody>
179</table>
180
181<table>
182 <tbody>
183 <tr>
184 <td valign="top">
185 <a href="https://github.com/sponsors/tannerlinsley/">
186 <img width='150' src="https://raw.githubusercontent.com/tannerlinsley/files/master/images/patreon/fans.png" />
187 </a>
188 </td>
189 <!-- <td>
190 <ul>
191 <li></li>
192 </ul>
193 </td> -->
194 <td>
195 <a href="https://github.com/sponsors/tannerlinsley" target="_blank">
196 Become a Fan!
197 </a>
198 </td>
199 </tr>
200 </tbody>
201</table>
202
203# Documentation
204
205- [Installation](#installation)
206- [Queries](#queries)
207 - [Query Keys](#query-keys)
208 - [Query Variables](#query-variables)
209 - [Dependent Queries](#dependent-queries)
210 - [Caching & Invalidation](#caching--invalidation)
211 - [Load-More & Infinite-Scroll Pagination](#load-more--infinite-scroll-pagination)
212 - [Scroll Restoration](#scroll-restoration)
213 - [Manual Querying](#manual-querying)
214 - [Retries](#retries)
215 - [Retry Delay](#retry-delay)
216 - [Prefetching](#prefetching)
217 - [Suspense Mode](#suspense-mode)
218 - [Fetch-on-render vs Fetch-as-you-render](#fetch-on-render-vs-fetch-as-you-render)
219- [Mutations](#mutations)
220 - [Basic Mutations](#basic-mutations)
221 - [Mutation Variables](#mutation-variables)
222 - [Invalidate and Refetch Queries from Mutations](#invalidate-and-refetch-queries-from-mutations)
223 - [Query Updates from Mutations](#query-updates-from-mutations)
224- [Manually or Optimistically Setting Query Data](#manually-or-optimistically-setting-query-data)
225- [Displaying Background Fetching Loading States](#displaying-background-fetching-loading-states)
226- [Displaying Global Background Fetching Loading State](#displaying-global-background-fetching-loading-state)
227- [Window-Focus Refetching](#window-focus-refetching)
228- [Custom Query Key Serializers (Experimental)](#custom-query-key-serializers-experimental)
229- [API](#api)
230 - [`useQuery`](#usequery)
231 - [`useMutation`](#usemutation)
232 - [`setQueryData`](#setquerydata)
233 - [`refetchQuery`](#refetchquery)
234 - [`prefetchQuery`](#prefetchQuery)
235 - [`refetchAllQueries`](#refetchallqueries)
236 - [`useIsFetching`](#useisfetching)
237 - [`ReactQueryConfigProvider`](#reactqueryconfigprovider)
238
239## Installation
240
241```bash
242$ npm i --save react-query
243# or
244$ yarn add react-query
245```
246
247## Queries
248
249To make a new query, call the `useQuery` hook with:
250
251- A **unique key for the query**
252- An **asynchronous function (or similar then-able)** to resolve the data
253
254```js
255const info = useQuery('todos', fetchTodoList)
256```
257
258The **unique key** you provide is used internally for refetching, caching, deduping related queries.
259
260This key can be whatever you'd like it to be as long as:
261
262- It changes when your query should be requested again
263- It is consistent across all instances of that specific query in your application
264
265The query `info` returned contains all information about the query and can be easily destructured and used in your component:
266
267```js
268function Todos() {
269 const { data, isLoading, error } = useQuery('todos', fetchTodoList)
270
271 return (
272 <div>
273 {isLoading ? (
274 <span>Loading...</span>
275 ) : error ? (
276 <span>Error: {error.message}</span>
277 ) : data ? (
278 <ul>
279 {data.map(todo => (
280 <li key={todo.id}>{todo.title}</li>
281 ))}
282 </ul>
283 ) : null}
284 </div>
285 )
286}
287```
288
289### Query Keys
290
291Since React Query uses a query's **unique key** for essentially everything, it's important to tailor them so that will change with your query requirements. In other libraries like Zeit's SWR, you'll see the use of URL's and GraphQL query template strings to achieve this, but we believe at scale, this becomes prone to typos and errors. To relieve this issue, you can pass a **tuple key** with a `string` and `object` of variables to deterministically get the the same key.
292
293> Pro Tip: Variables passed in the key are automatically passed to your query function!
294
295All of the following queries would result in using the same key:
296
297```js
298useQuery(['todos', { status, page }])
299useQuery(['todos', { page, status }])
300useQuery(['todos', { page, status, other: undefined }])
301```
302
303### Query Variables
304
305To use external props, state, or variables in a query function, pass them as a variables in your query key! They will be passed through to your query function as the first parameter.
306
307```js
308function Todos({ status }) {
309 const { data, isLoading, error } = useQuery(
310 ['todos', { status, page }],
311 fetchTodoList // This is the same as `fetchTodoList({ status, page })`
312 )
313}
314```
315
316Whenever a query's key changes, the query will automatically update:
317
318```js
319function Todos() {
320 const [page, setPage] = useState(0)
321
322 const { data, isLoading, error } = useQuery(
323 ['todos', { page }],
324 fetchTodoList
325 )
326
327 const onNextPage = () => {
328 setPage(page => page + 1)
329 }
330
331 return (
332 <>
333 {/* ... */}
334 <button onClick={onNextPage}>Load next page</button>
335 </>
336 )
337}
338```
339
340### Dependent Queries
341
342React Query makes it easy to make queries that depend on other queries for both:
343
344- Parallel Queries (avoiding waterfalls) and
345- Serial Queries (when a piece of data is required for the next query to happen.
346
347To do this, you can use the following 2 approaches:
348
349#### Pass a falsey query key
350
351If a query isn't ready to be requested yet, just pass a falsey value as the query key:
352
353```js
354const { data: user } = useQuery(['user', { userId }])
355const { data: projects } = useQuery(user && ['projects', { userId: user.id }]) // User is `null`, so the query key will be falsey
356```
357
358#### Use a query key function
359
360If a function is passed, the query will not execute until the function can be called without throwing:
361
362```js
363const { data: user } = useQuery(['user', { userId }])
364const { data: projects } = useQuery(() => ['projects', { userId: user.id }]) // This will throw until `user` is available
365```
366
367#### Mix them together!
368
369```js
370const [ready, setReady] = React.useState(false)
371const { data: user } = useQuery(ready && ['user', { userId }]) // Wait for ready to be truthy
372const { data: projects } = useQuery(
373 () => ['projects', { userId: user.id }] // Wait for user.id to become available (and not throw)
374```
375
376### Caching & Invalidation
377
378React Query caching is automatic out of the box. It uses a `stale-while-revalidate` in-memory caching strategy together with robust query deduping to to always ensure a query's data is only cached when it's needed and only cached once even if that query is used multiple times across your application.
379
380At a glance:
381
382- The cache is keyed on unique `query + variables` combinations.
383- By default query results become **stale** immediately after a successful fetch. This can be configured using the `staleTime` option at both the global and query-level)
384- Stale queries are automatically refetched whenever their **query keys change (this includes variables used in query key tuples)** or when **new usages/instances** of a query are mounted.
385- By default query results are **always** cached **when in use**.
386- If and when a query is no longer being used, it becomes **inactive** and by default is cached in the background for **5 minutes**. This time can be configured using the `cacheTime` option at both the global and query-level
387- After a query is inactive for the `cacheTime` specified (defaults to 5 minutes), the query is deleted and garbage collected.
388
389<details>
390 <summary>A more detailed example of the caching lifecycle</summary>
391
392Let's assume we are using the default `cacheTime` of **5 minutes** and the default `staleTime` of `0`.
393
394- A new instance of `useQuery('todos', fetchTodos)` mounts
395 - Since no other queries have been made with this query + variable combination, this query will show a hard loading state and make a network request to fetch the data.
396 - It will then cache the data using `'todos'` and `` as the unique identifiers for that cache.
397 - A stale invalidation is scheduled using the `staleTime` option as a delay (defaults to `0`, or immediately).
398- A second instance of `useQuery('todos', fetchTodos)` mounts elsewhere
399 - Because this exact data exist in the cache from the first instance of this query, that data is immediately returned from the cache
400 - Since the query is stale, it is refetched in the background automatically
401- Both instances of the `useQuery('todos', fetchTodos)` query are unmount and no longer in use.
402 - Since there are no more active instances to this query, a cache timeout is set using `cacheTime` to delete and garbage collect the query (defaults to **5 minutes**).
403- No more instances of `useQuery('todos', fetchTodos)` appear within **5 minutes**
404 - This query and its data is deleted and garbage collected.
405
406</details>
407
408### Load-More & Infinite-Scroll Pagination
409
410Rendering paginated lists that can "load more" data or "infinite scroll" is a common UI pattern. React Query supports some useful features for querying these types of lists. Let's assume we have an API that returns pages of `todos` 3 at a time based on a `cursor` index:
411
412```js
413fetch('/api/projects?cursor=0'
414// { data: [...], nextId: 3}
415fetch('/api/projects?cursor=3'
416// { data: [...], nextId: 6}
417fetch('/api/projects?cursor=6'
418// { data: [...], nextId: 9}
419```
420
421Using the `nextId` value in each page's response, we can configure `useQuery` to fetch more pages as needed:
422
423- Configure your query function to use optional pagination variables. We'll send through the `nextId` as the `cursor` for the next page request
424- Set the `paginated` option to `true`
425- Define a `getCanFetchMore` option to know if there is more data to load (it receives the `lastPage` and `allPages` as parameters)
426
427```js
428import { useQuery } from 'react-query'
429
430function Todos() {
431 const {
432 data: pages,
433 isLoading,
434 isFetching,
435 isFetchingMore,
436 fetchMore,
437 canFetchMore,
438 } = useQuery(
439 'todos',
440 ({ nextId } = {}) => fetch('/api/projects?cursor=' + (nextId || 0)),
441 {
442 paginated: true,
443 getCanFetchMore: (lastPage, allPages) => next.nextId,
444 }
445 )
446
447 // ...
448}
449```
450
451You'll notice a few new things now:
452
453- `data` is now an array of pages that contain query results, instead of the query results themselves
454- A `fetchMore` function is now available
455- A `canFetchMore` boolean is now available
456- An `isFetchingMore` boolean is now available
457
458These can now be used to render a "load more" list (this example uses an `offset` key):
459
460```js
461import { useQuery } from 'react-query'
462
463function Todos() {
464 const {
465 data: pages,
466 isLoading,
467 isFetching,
468 isFetchingMore,
469 fetchMore,
470 canFetchMore,
471 } = useQuery(
472 'projects',
473 ({ offset } = {}) => fetch('/api/projects?offset=' + (offset || 0)),
474 {
475 paginated: true,
476 getCanFetchMore: (lastPage, allPages) => next.nextId,
477 }
478 )
479
480 const loadMore = async () => {
481 try {
482 // Get the last page
483 const lastPage = data[data.length - 1]
484 // Get the last item's ID
485 const lastItemId = lastPage[lastPage.length - 1].id
486 // Fetch more with the offset ID + 1
487 await fetchMore({
488 offset: lastItemId + 1,
489 })
490 } catch {}
491 }
492
493 return isLoading ? (
494 <p>Loading...</p>
495 ) : data ? (
496 <>
497 {data.map((page, i) => (
498 <React.Fragment key={i}>
499 {page.data.map(project => (
500 <p key={project.id}>{project.name}</p>
501 ))}
502 </React.Fragment>
503 ))}
504 <div>
505 {canFetchMore ? (
506 <button onClick={loadMore} disabled={isFetchingMore}>
507 {isFetchingMore ? 'Loading more...' : 'Load More'}
508 </button>
509 ) : (
510 'Nothing more to fetch.'
511 )}
512 </div>
513 <div>
514 {isFetching && !isFetchingMore ? 'Background Updating...' : null}
515 </div>
516 </>
517 ) : null
518}
519```
520
521#### What happens when a paginated query needs to be refetched?\*\*
522
523When a paginated query becomes `stale` and needs to be refetched, each page is fetched `individually` with the same variables that were used to request it originally. If a paginated query's results are ever removed from the cache, the pagination restarts at the initial state with a single page being requested.
524
525### Scroll Restoration
526
527Out of the box, "scroll restoration" Just Works™️ in React Query. The reason for this is that query results are cached and retrieved synchronously when rendered. As long as a query is cached and has not been garbage collected, you should never experience problems with scroll restoration.
528
529### Manual Querying
530
531If you ever want to disable a query from automatically running, you can use the `manual = true` option. When `manual` is set to true:
532
533- The query will not automatically refetch due to changes to their query function or variables.
534- The query will not automatically refetch due to `refetchQueries` options in other queries or via `refetchQuery` calls.
535
536```js
537function Todos() {
538 const { data, isLoading, error, refetch, isFetching } = useQuery(
539 'todos',
540 fetchTodoList,
541 {
542 manual: true,
543 }
544 )
545
546 return (
547 <>
548 <button onClick={() => refetch()}>Fetch Todos</button>
549
550 {isLoading ? (
551 <span>Loading...</span>
552 ) : error ? (
553 <span>Error: {error.message}</span>
554 ) : data ? (
555 <>
556 <ul>
557 {data.map(todo => (
558 <li key={todo.id}>{todo.title}</li>
559 ))}
560 </ul>
561 </>
562 ) : null}
563 </>
564 )
565}
566```
567
568> Pro Tip: Don't use `manual` for dependent queries. Use [Dependent Queries](#dependent-queries) instead!
569
570### Retries
571
572When a `useQuery` query fails (the function throws an error), React Query will automatically retry the query if that query's request has not reached the max number of consecutive retries (defaults to `3`).
573
574You can configure retries both on a global level and an individual query level.
575
576- Setting `retry = false` will disable retries
577- Setting `retry = 6` will retry failing requests 6 times before showing the final error thrown by the function
578- Setting `retry = true` will infinitely retry failing requests.
579
580```js
581import { useQuery } from 'react-query'
582
583// Make specific query retry a certain number of times
584const { data, isLoading, error } = useQuery(
585 ['todos', { page: 1 }],
586 fetchTodoList,
587 {
588 retry: 10, // Will retry failed requests 10 times before displaying an error
589 }
590)
591```
592
593### Retry Delay
594
595By default, retries in React Query do not happen immediately after a request fails. As is standard, a back-off delay is gradually applied to each retry attempt.
596
597The default `retryDelay` is set to double (starting at `1000`ms) with each attempt, but not exceed 30 seconds:
598
599```js
600// Configure for all queries
601import { ReactQueryConfigProvider } from 'react-query'
602
603const queryConfig = {
604 retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000),
605}
606
607function App() {
608 return (
609 <ReactQueryConfigProvider config={queryConfig}>
610 ...
611 </ReactQueryConfigProvider>
612 )
613}
614```
615
616Though it is not recommended, you can obviously override the `retryDelay` function/integer in both the Provider and individual query options. If set to an integer instead of a function the delay will always be the same amount of time:
617
618```js
619const { data, isLoading, error } = useQuery('todos', fetchTodoList, {
620 retryDelay: 10000, // Will always wait 1000ms to retry, regardless of how many retries
621})
622```
623
624### Prefetching
625
626If you're lucky enough, you may know enough about what your users will do to be able to prefetch the data they need before it's needed! If this is the case, then you're in luck. You can use the `prefetchQuery` function to prefetch the results of a query to be placed into the cache:
627
628```js
629import { prefetchQuery } from 'react-query'
630
631const prefetchTodos async () => {
632 const queryData = await prefetchQuery('todos', () => fetch('/todos'))
633 // The results of this query will be cached like a normal query
634}
635```
636
637The next time a `useQuery` instance is used for a prefetched query, it will use the cached data! If no instances of `useQuery` appear for a prefetched query, it will be deleted and garbage collected after the time specified in `cacheTime`.
638
639### Suspense Mode
640
641React Query can also be used with React's new Suspense for Data Fetching API's. To enable this mode, you can set either the global or query level config's `suspense` option to `true`.
642
643Global configuration:
644
645```js
646// Configure for all queries
647import { ReactQueryConfigProvider } from 'react-query'
648
649const queryConfig = {
650 suspense: true,
651}
652
653function App() {
654 return (
655 <ReactQueryConfigProvider config={queryConfig}>
656 ...
657 </ReactQueryConfigProvider>
658 )
659}
660```
661
662Query configuration:
663
664```js
665const { useQuery } from 'react-query'
666
667// Enable for an individual query
668useQuery(queryKey, queryFn, { suspense: true })
669```
670
671When using suspense mode, `isLoading` and `error` states will be replaced by usage of the `React.Suspense` component (including the use of the `fallback` prop and React error boundaries for catching errors. Please see the [Suspense Example](https://codesandbox.io/s/github/tannerlinsley/react-query/tree/master/examples/sandbox) for more information on how to set up suspense mode.
672
673#### Fetch-on-render vs Fetch-as-you-render
674
675Out of the box, React Query in `suspense` mode works really well as a **Fetch-on-render** solution with no additional configuration. However, if you want to take it to the next level and implement a `Fetch-as-you-render` model, we recommend implementing [Prefetching](#prefetching) on routing and/or user interactions events to initialize queries before they are needed.
676
677## Mutations
678
679Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, React Query exports a `useMutation` hook.
680
681### Basic Mutations
682
683Assuming the server implements a ping mutation, that returns "pong" string, here's an example of the most basic mutation:
684
685```js
686const PingPong = () => {
687 const [mutate, { data, isLoading, error }] = useMutation(pingMutation)
688
689 const onPing = async () => {
690 try {
691 const data = await mutate()
692 console.log(data)
693 // { ping: 'pong' }
694 } catch {
695 // Uh oh, something went wrong
696 }
697 }
698 return <button onClick={onPing}>Ping</button>
699}
700```
701
702Mutations without variables are not that useful, so let's add some variables to closer match reality.
703
704### Mutation Variables
705
706To pass `variables` to your `mutate` function, call `mutate` with an object.
707
708```js
709const CreateTodo = () => {
710 const [title, setTitle] = useState('')
711 const [mutate] = useMutation(createTodo)
712
713 const onCreateTodo = async e => {
714 // Prevent the form from refreshing the page
715 e.preventDefault()
716
717 try {
718 await mutate({ title })
719 // Todo was successfully created
720 } catch (error) {
721 // Uh oh, something went wrong
722 }
723 }
724
725 return (
726 <form onSubmit={onCreateTodo}>
727 <input
728 type="text"
729 value={title}
730 onChange={e => setTitle(e.target.value)}
731 />
732 <br />
733 <button type="submit">Create Todo</button>
734 </form>
735 )
736}
737```
738
739Even with just variables, mutations aren't all that special, but when used with the `refetchQueries` and `updateQuery` options, they become a very powerful tool.
740
741### Invalidate and Refetch Queries from Mutations
742
743When a mutation succeeds, it's likely that other queries in your application need to update. Where other libraries that use normalized caches would attempt to update locale queries with the new data imperatively, React Query avoids the pitfalls that come with normalized caches and prescribes **atomic updates** instead of partial cache manipulation.
744
745For example, assume we have a mutation to post a new todo:
746
747```js
748const [mutate] = useMutation(postTodo)
749```
750
751When a successful `postTodo` mutation happens, we likely want all `todos` queries to get refetched to show the new todo item. To do this, you can use the `refetchQueries` option when calling a mutation's `mutate` function.
752
753```js
754// When this mutation succeeds, any queries with the `todos` or `reminders` query key will be refetched
755mutate(newTodo, { refetchQueries: ['todos', 'reminders'], })
756
757// The 3 queries below will be refetched when the mutation above succeeds
758const todoListQuery = useQuery('todos', fetchTodoList)
759const todoListQuery = useQuery(['todos', { page: 1 }, fetchTodoList)
760const remindersQuery = useQuery('reminders', fetchReminders)
761```
762
763You can even refetch queries with specific variables by passing a query key tuple to `refetchQueries`:
764
765```js
766mutate(newTodo, { refetchQueries: [['todos', { status: 'done' }]] })
767
768// The query below will be refetched when the mutation above succeeds
769const todoListQuery = useQuery(['todos', { status: 'done' }], fetchTodoList)
770// However, the following query below will NOT be refetched
771const todoListQuery = useQuery('todos', fetchTodoList)
772```
773
774If you want to **only** refetch `todos` queries that don't have variables, you can pass a tuple with `variables` set to `false`:
775
776```js
777mutate(newTodo, { refetchQueries: [['todos', false]] })
778
779// The query below will be refetched when the mutation above succeeds
780const todoListQuery = useQuery(['todos'], fetchTodoList)
781// However, the following query below will NOT be refetched
782const todoListQuery = useQuery(['todos', { status: 'done' }], fetchTodoList)
783```
784
785If you prefer that the promise returned from `mutate()` only resolves **after** any `refetchQueries` have been refetched, you can pass the `waitForRefetchQueries = true` option to `mutate`:
786
787```js
788const [mutate] = useMutation(addTodo, { refetchQueries: ['todos'] })
789
790const run = async () => {
791 try {
792 await mutate(todo, { waitForRefetchQueries: true })
793 console.log('I will only log after all refetchQueries are done refetching!')
794 } catch {}
795}
796```
797
798It's important to note that `refetchQueries` by default will only happen after a successful mutation (the mutation function doesn't throw an error). If you would like to refetch the `refetchQueries` regardless of this, you can set `refetchQueriesOnFailure` to `true` in your `mutate` options:
799
800```js
801const [mutate] = useMutation(addTodo, { refetchQueries: ['todos'] })
802
803const run = async () => {
804 try {
805 await mutate(todo, { refetchQueriesOnFailure: true })
806 // Even if the above mutation fails, any `todos` queries will still be refetched.
807 } catch {}
808}
809```
810
811### Query Updates from Mutations
812
813When dealing with mutations that **update** objects on the server, it's common for the new object to be automatically returned in the response of the mutation. Instead of invalidating any queries for that item and wasting a network call to refetch them again, we can take advantage of the object returned by the mutation function and update any query responses with that data that match that query using the `updateQuery` option:
814
815```js
816const [mutate] = useMutation(editTodo)
817
818mutate(
819 {
820 id: 5,
821 name: 'Do the laundry',
822 },
823 {
824 updateQuery: ['todo', { id: 5 }],
825 }
826)
827
828// The query below will be updated with the response from the mutation above when it succeeds
829const { data, isLoading, error } = useQuery(['todo', { id: 5 }], fetchTodoByID)
830```
831
832## Manually or Optimistically Setting Query Data
833
834In rare circumstances, you may want to manually update a query's response before it has been refetched. To do this, you can use the exported `setQueryData` function:
835
836```js
837import { setQueryData } from 'react-query'
838
839// Full replacement
840setQueryData(['todo', { id: 5 }], newTodo)
841
842// or functional update
843setQueryData(['todo', { id: 5 }], previous => ({ ...previous, status: 'done' }))
844```
845
846**Most importantly**, when manually setting a query response, it naturally becomes out-of-sync with it's original source. To ease this issue, `setQueryData` automatically triggers a background refresh of the query after it's called to ensure it eventually synchronizes with the original source.
847
848Should you choose that you do _not_ want to refetch the query automatically, you can set the `shouldRefetch` option to `false`:
849
850```js
851import { setQueryData } from 'react-query'
852
853// Mutate, but do not automatically refetch the query in the background
854setQueryData(['todo', { id: 5 }], newTodo, {
855 shouldRefetch: false,
856})
857```
858
859## Displaying Background Fetching Loading States
860
861A query's `isLoading` boolean is usually sufficient to show the initial hard-loading state for a query, but sometimes you may want to display a more subtle indicator that a query is refetching in the background. To do this, queries also supply you with an `isFetching` boolean that you can use to show that it's in a fetching state:
862
863```js
864function Todos() {
865 const { data: todos, isLoading, isFetching } = useQuery('todos', fetchTodos)
866
867 return isLoading ? (
868 <span>Loading...</span>
869 ) : todos ? (
870 <>
871 {isFetching ? <div>Refreshing...</div> : null}
872
873 <div>
874 {todos.map(todo => (
875 <Todo todo={todo} />
876 ))}
877 </div>
878 </>
879 ) : null
880}
881```
882
883## Displaying Global Background Fetching Loading State
884
885In addition to individual query loading states, if you would like to show a global loading indicator when **any** queries are fetching (including in the background), you can use the `useIsFetching` hook:
886
887```js
888import { useIsFetching } from 'react-query'
889
890function GlobalLoadingIndicator() {
891 const isFetching = useIsFetching()
892
893 return isFetching ? (
894 <div>Queries are fetching in the background...</div>
895 ) : null
896}
897```
898
899## Window-Focus Refetching
900
901If a user leaves your application and returns to stale data, you may want to trigger an update in the background to update any stale queries. Thankfully, **React Query does this automatically for you**, but if you choose to disable it, you can use the `ReactQueryConfigProvider`'s `refetchAllOnWindowFocus` option to disable it:
902
903```js
904const queryConfig = { refetchAllOnWindowFocus: false }
905
906function App() {
907 return (
908 <ReactQueryConfigProvider config={queryConfig}>
909 ...
910 </ReactQueryConfigProvider>
911 )
912}
913```
914
915## Custom Query Key Serializers (Experimental)
916
917> **WARNING:** This is an advanced and experimental feature. There be dragons here. Do not change the Query Key Serializer unless you know what you are doing and are fine with encountering edge cases in the React Query API
918
919If you absolutely despise the default query key and variable syntax, you can replace the default query key serializer with your own by using the `ReactQueryConfigProvider` hook's `queryKeySerializerFn` option:
920
921```js
922const queryConfig = {
923 queryKeySerializerFn: userQueryKey => {
924 // Your custom logic here...
925
926 return [fullQueryHash, queryGroupId, variablesHash, variables]
927 },
928}
929
930function App() {
931 return (
932 <ReactQueryConfigProvider config={queryConfig}>
933 ...
934 </ReactQueryConfigProvider>
935 )
936}
937```
938
939- `userQueryKey: any`
940 - This is the queryKey passed in `useQuery` and all other public methods and utilities exported by React Query.
941- `fullQueryHash: string`
942 - This must be a unique `string` representing the query and variables.
943 - It must be stable and deterministic and should not change if things like the order of variables is changed or shuffled.
944- `queryGroupId: string`
945 - This must be a unique `string` representing only the query type without any variables
946 - It must be stable and deterministic and should not change if the variables of the query change
947- `variablesHash: string`
948 - This must be a unique `string` representing only the variables of the query
949 - It must be stable and deterministic and should not change if things like the order of variables is changed or shuffled.
950- `variables: any`
951 - This is the object that will be passed to the `queryFn` when using `useQuery`.
952
953> An additional `stableStringify` utility is also exported to help with stringifying objects to have sorted keys.
954
955#### URL Query Key Serializer Example
956
957The example below shows how to build your own serializer for use with urls and use it with React Query:
958
959```js
960import { ReactQueryConfigProvider, stableStringify } from 'react-query'
961
962function urlQueryKeySerializer(queryKey) {
963 // Deconstruct the url
964 let [url, params = ''] = queryKey.split('?')
965
966 // Build the variables object
967 let variables = {}
968 params
969 .split('&')
970 .filter(Boolean)
971 .forEach(param => {
972 const [key, value] = param.split('=')
973 variables[key] = value
974 })
975
976 // Use stableStringify to turn variables into a stable string
977 const variablesHash = Object.keys(variables).length
978 ? stableStringify(variables)
979 : ''
980
981 // Remove trailing slashes from the url to make an ID
982 const queryGroupId = url.replace(/\/{1,}$/, '')
983
984 const queryHash = `${id}_${variablesHash}`
985
986 return [queryHash, queryGroupId, variablesHash, variables]
987}
988
989const queryConfig = {
990 queryKeySerializerFn: urlQueryKeySerializer,
991}
992
993function App() {
994 return (
995 <ReactQueryConfigProvider config={queryConfig}>
996 ...
997 </ReactQueryConfigProvider>
998 )
999}
1000
1001// Heck, you can even make your own custom useQueryHook!
1002
1003function useUrlQuery(url, options) {
1004 return useQuery(url, () => axios.get(url).then(res => res.data))
1005}
1006
1007// Use it in your app!
1008
1009function Todos() {
1010 const todosQuery = useUrlQuery(`/todos`)
1011}
1012
1013function FilteredTodos({ status = 'pending' }) {
1014 const todosQuery = useFunctionQuery([getTodos, { status }])
1015}
1016
1017function Todo({ id }) {
1018 const todoQuery = useUrlQuery(`/todos/${id}`)
1019}
1020
1021refetchQuery('/todos')
1022refetchQuery('/todos?status=pending')
1023refetchQuery('/todos/5')
1024```
1025
1026#### Function Query Key Serializer Example
1027
1028The example below shows how to you build your own functional serializer and use it with React Query:
1029
1030```js
1031import { ReactQueryConfigProvider, stableStringify } from 'react-query'
1032
1033// A map to keep track of our function pointers
1034const functionSerializerMap = new Map()
1035
1036function functionQueryKeySerializer(queryKey) {
1037 if (!queryKey) {
1038 return []
1039 }
1040
1041 let queryFn = queryKey
1042 let variables
1043
1044 if (Array.isArray(queryKey)) {
1045 queryFn = queryKey[0]
1046 variables = queryKey[1]
1047 }
1048
1049 // Get or create an ID for the function pointer
1050 const queryGroupId = functionSerializerMap.get(queryFn) || (() => {
1051 const id = Date.now()
1052 functionSerializerMap.set(queryFn, id)
1053 return id
1054 })()
1055
1056 const variablesIsObject = isObject(variables)
1057
1058 const variablesHash = variablesIsObject ? stableStringify(variables) : ''
1059
1060 const queryHash = `${queryGroupId}_${variablesHash}`
1061
1062 return [
1063 queryHash,
1064 queryGroupId,
1065 variablesHash,
1066 variables,
1067 ]
1068}
1069
1070const queryConfig = {
1071 queryKeySerializerFn: functionQueryKeySerializer,
1072}
1073
1074function App() {
1075 return (
1076 <ReactQueryConfigProvider config={queryConfig}>
1077 ...
1078 </ReactQueryConfigProvider>
1079 )
1080}
1081// Heck, you can even make your own custom useQueryHook!
1082
1083function useFunctionQuery(functionTuple, options) {
1084 const [queryFn, variables] = Array.isArray(functionTuple) ? functionTuple : [functionTuple]
1085 return useQuery(functionTuple, queryFn, options)
1086}
1087
1088// Use it in your app!
1089
1090function Todos() {
1091 const todosQuery = useFunctionQuery(getTodos)
1092}
1093
1094function FilteredTodos({ status = 'pending' }) {
1095 const todosQuery = useFunctionQuery([getTodos, { status }])
1096}
1097
1098function Todo({ id }) {
1099 const todoQuery = useFunctionQuery([getTodo, { id }])
1100}
1101
1102refetchQuery(getTodos)
1103refetchQuery([getTodos, { status: 'pending' }])
1104refetchQuery([getTodo, { id: 5}])
1105```
1106
1107# API
1108
1109## `useQuery`
1110
1111```js
1112const {
1113 data,
1114 error,
1115 isFetching,
1116 isCached,
1117 failureCount,
1118 isLoading,
1119 refetch,
1120 // with pagination mode enabled
1121 isFetchingMore,
1122 canFetchMore,
1123 fetchMore,
1124} = useQuery(queryKey, queryFn, {
1125 manual,
1126 pagination,
1127 getCanFetchMore,
1128 staleTime,
1129 retry,
1130 retryDelay,
1131 onSuccess,
1132 onError,
1133 suspense,
1134})
1135```
1136
1137### Options
1138
1139- `queryKey: String | [String, Variables: Object] | falsey | Function => queryKey`
1140 - **Required**
1141 - The query key to use for this query.
1142 - If a string is passed, it will be used as the query key
1143 - If a `[String, Object]` tuple is passed, they will be serialized into a stable query key. See [Query Keys](#query-keys) for more information.
1144 - If a falsey value is passed, the query will be disabled and not run automatically.
1145 - If a function is passed, it should resolve to any other valid query key type. If the function throws, the query will be disabled and not run automatically.
1146 - The query will automatically update when this key changes (if the key is not falsey and if `manual` is not set to `true`)
1147 - `Variables: Object`
1148 - If a tuple with variables is passed, this object should be **serializable**.
1149 - Nested arrays and objects are supported
1150 - The order of object keys is sorted to be stable before being serialized into the query key
1151- `queryFn: Function(variables) => Promise(data/error)`
1152 - **Required**
1153 - The function that the query will use to request data
1154 - Optionally receives the `variables` object passed from either the query key tuple (`useQuery(['todos', variables], queryFn)`) or the `refetch` method's `variables` option, eg. `refetch({ variables })`
1155 - Must return a promise that will either resolves data or throws an error.
1156- `pagination: Boolean`
1157 - Set this to `true` to enable pagination mode
1158 - In this mode, new pagination utilities are returned from `useQuery` and `data` becomes an array of page results
1159- `manual: Boolean`
1160 - Set this to `true` to disable automatic refetching when the query mounts or changes query keys.
1161 - To refetch the query, use the `refetch` method returned from the `useQuery` instance.
1162- `getCanFetchMore: Function(lastPage, allPages) => Boolean`
1163 - **Required if using `pagination` mode**
1164 - When using `pagination` mode, this function should return `true` if there is more data than can be fetched.
1165- `retry: Boolean | Int`
1166 - If `false`, failed queries will not retry by default
1167 - If `true`, failed queries will retry infinitely
1168 - If set to an `Int`, eg. `3`, failed queries will retry until the failed query count meets that number
1169- `retryDelay: Function(retryAttempt: Int) => Int`
1170 - This function receives a `retryAttempt` integer and returns the delay to apply before the next attempt in milliseconds
1171 - A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff
1172 - A function like `attempt => attempt * 1000` applies linear backoff.
1173- `staleTime: Int`
1174 - The time in milliseconds that cache data remains fresh. After a successful cache update, that cache data will become stale after this duration
1175- `cacheTime: Int`
1176 - The time in milliseconds that unused/inactive cache data remains in memory. When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration.
1177- `refetchInterval: false | Integer`
1178 - Optional
1179 - If set to a number, all queries will continuously refetch at this frequency in milliseconds
1180- `onError: Function(err) => void`
1181 - Optional
1182 - This function will fire if the query encounters an error (after all retries have happened) and will be passed the error.
1183- `onSucess: Function(data) => data`
1184 - Optional
1185 - This function will fire any time the query successfully fetches new data.
1186- `suspense: Boolean`
1187 - Optional
1188 - Set this to `true` to enable suspense mode.
1189 - When `true`, `useQuery` will suspend when `isLoading` would normally be `true`
1190 - When `true`, `useQuery` will throw runtime errors when `error` would normally be truthy
1191
1192### Returns
1193
1194- `data: null | Any`
1195 - Defaults to `null`
1196 - The last successfully resolved data for the query.
1197- `error: null | Error`
1198 - The error object for the query, if an error was thrown.
1199- `isLoading: Boolean`
1200 - Will be `true` if the query is both fetching and does not have any cached data to display.
1201- `isFetching: Boolean`
1202 - Will be `true` if the query is currently fetching, including background fetching.
1203- `isCached: Boolean`
1204 - Will be `true` if the query's response is currently cached.
1205- `failureCount: Integer`
1206 - The failure count for the query.
1207 - Incremented every time the query fails.
1208 - Reset to `0` when the query succeeds.
1209- `refetch: Function({ variables: Object, merge: Function, disableThrow: Boolean })`
1210 - A function to manually refetch the query.
1211 - Supports custom variables (useful for "fetch more" calls)
1212 - Supports custom data merging (useful for "fetch more" calls)
1213 - Set `disableThrow` to true to disable this function from throwing if an error is encountered.
1214- `isFetchingMore: Boolean`
1215 - If using `pagination` mode, this will be `true` when fetching more results using the `fetchMore` function.
1216- `canFetchMore: Boolean`
1217 - If using `pagination` mode, this will be `true` if there is more data to be fetched (known via the required `getCanFetchMore` option function)
1218- `fetchMore: Function(variables) => Promise`
1219 - If using `pagination` mode, this function allows you to fetch the next "page" of results.
1220 - `variables` should be an object that is passed to your query function to retrieve the next page of results
1221
1222## `useMutation`
1223
1224```js
1225const [mutate, { data, isLoading, error }] = useMutation(mutationFn, {
1226 refetchQueries,
1227 refetchQueriesOnFailure,
1228})
1229
1230const promise = mutate(variables, { updateQuery, waitForRefetchQueries })
1231```
1232
1233### Options
1234
1235- `mutationFn: Function(variables) => Promise`
1236 - **Required**
1237 - A function that performs an asynchronous task and returns a promise
1238- `refetchQueries: Array<QueryKey>`
1239 - Optional
1240 - When the mutation succeeds, these queries will be automatically refetched
1241 - Must be an array of query keys, eg. `['todos', ['todo', { id: 5 }], 'reminders']`
1242- `refetchQueriesOnFailure: Boolean`
1243 - Defaults to `false`
1244 - Set this to `true` if you want `refetchQueries` to be refetched regardless of the mutation succeeding.
1245- `variables: any`
1246 - Optional
1247 - The variables object to pass tot he `mutationFn`
1248- `updateQuery: QueryKey`
1249 - Optional
1250 - The query key for the individual query to update with the response from this mutation.
1251 - Suggested use is for `update` mutations that regularly return the updated data with the mutation. This saves you from making another unnecessary network call to refetch the data.
1252- `waitForRefetchQueries: Boolean`
1253 - Optional
1254 - If set to `true`, the promise returned by `mutate()` will not resolve until refetched queries are resolved as well.
1255
1256### Returns
1257
1258- `mutate: Function(variables, { updateQuery })`
1259 - The mutation function you can call with variables to trigger the mutation and optionally update a query with its response.
1260- `data: null | Any`
1261 - Defaults to `null`
1262 - The last successfully resolved data for the query.
1263- `error: null | Error`
1264 - The error object for the query, if an error was thrown.
1265- `isLoading: Boolean`
1266 - Will be `true` if the query is both fetching and does not have any cached data
1267- `promise: Promise`
1268 - The promise that is returned by the `mutationFn`
1269
1270## `setQueryData`
1271
1272`setQueryData` is a function for imperatively updating the response of a query. By default, this function also triggers a background refetch to ensure that the data is eventually consistent with the remote source, but this can be disabled.
1273
1274```js
1275import { setQueryData } from 'react-query'
1276
1277const maybePromise = setQueryData(queryKey, data, { shouldRefetch })
1278```
1279
1280### Options
1281
1282- `queryKey: QueryKey`
1283 - **Required**
1284 - The query key for the individual query to update with new data.
1285- `data: any | Function(old) => any`
1286 - **Required**
1287 - Must either be the new data or a function that receives the old data and returns the new data
1288- `shouldRefetch: Boolean`
1289 - Optional
1290 - Defaults to `true`
1291 - Set this to `false` to disable the automatic background refetch from happening
1292
1293### Returns
1294
1295- `maybePromise: undefined | Promise`
1296 - If `shouldRefetch` is `true`, a promise is returned that will either resolve when the query refetch is complete or will reject if the refetch fails (after its respective retry configurations is done).
1297
1298## `refetchQuery`
1299
1300`refetchQuery` is a function that can ge used to trigger a refetch of
1301
1302- A group of active queries
1303- A single, specific query
1304
1305By default, `refetchQuery` will only refetch stale queries, but the `force` option can be used to include non-stale ones.
1306
1307```js
1308import { refetchQuery } from 'react-query'
1309
1310const promise = refetchQuery(queryKey, { force })
1311```
1312
1313### Options
1314
1315- `queryKey: QueryKey`
1316 - **Required**
1317 - The query key for the query or query group to refetch.
1318 - If a single `string` is passed, any queries using that `string` or any tuple key queries that include that `string` (eg. passing `todos` would refetch both `todos` and `['todos', { status: 'done' }]`).
1319 - If a tuple key is passed, only the exact query with that key will be refetched (eg. `['todos', { status: 'done' }]` will only refetch queries with that exact key)
1320 - If a tuple key is passed with the `variables` slot set to `false`, then only queries that match the `string` key and have no variables will be refetched (eg. `['todos', false]` would only refetch `todos` and not `['todos', { status: 'done' }]`)
1321- `force: Boolean`
1322 - Optional
1323 - Set this to true to force all queries to refetch instead of only stale ones.
1324
1325### Returns
1326
1327- `promise: Promise`
1328 - A promise is returned that will either resolve when all refetch queries are complete or will reject if any refetch queries fail (after their respective retry configurations are done).
1329
1330## `refetchAllQueries`
1331
1332`refetchAllQueries` is a function for imperatively triggering a refetch of all queries. By default, it will only refetch stale queries, but the `force` option can be used to refetch all queries, including non-stale ones.
1333
1334```js
1335import { refetchAllQueries } from 'react-query'
1336
1337const promise = refetchAllQueries({ force, includeInactive })
1338```
1339
1340### Options
1341
1342- `force: Boolean`
1343 - Optional
1344 - Set this to `true` to force all queries to refetch instead of only stale ones.
1345- `includeInactive: Boolean`
1346 - Optional
1347 - Set this to `true` to also refetch inactive queries.
1348 - Overrides the `force` option to be `true`, regardless of it's value.
1349
1350### Returns
1351
1352- `promise: Promise`
1353 - A promise is returned that will either resolve when all refetch queries are complete or will reject if any refetch queries fail (after their respective retry configurations are done).
1354
1355## `useIsFetching`
1356
1357`useIsFetching` is an optional hook that returns true if any query in your application is loading for fetching in the background (useful for app-wide loading indicators)
1358
1359```js
1360import { useIsFetching } from 'react-query'
1361
1362const isFetching = useIsFetching()
1363```
1364
1365### Returns
1366
1367- `isFetching: Boolean`
1368 - Will be `true` if any query in your application is loading or fetching in the background
1369
1370## `prefetchQuery`
1371
1372`prefetchQuery` is a function that can ge used to fetch and cache a query response for later before it is needed or rendered with `useQuery`. **Please note** that `prefetch` will not trigger a query fetch if the query is already cached. If you wish, you can force a prefetch for non-stale queries by using the `force` option:
1373
1374```js
1375import { prefetchQuery } from 'react-query'
1376
1377const data = await prefetchQuery(queryKey, queryFn, { force, ...config })
1378```
1379
1380### Options
1381
1382The options for `prefetchQuery` are exactly the same as those of [`useQuery`](#usequery), with the exception of a `force` option:
1383
1384- `force: Boolean`
1385 - Optional
1386 - Set this to true to prefetch a query **even if it is stale**
1387
1388### Returns
1389
1390- `promise: Promise`
1391 - A promise is returned that will either resolve with the **query's response data**, or throw with an **error**.
1392
1393## `ReactQueryConfigProvider`
1394
1395`ReactQueryConfigProvider` is an optional provider component and can be used to define defaults for all instances of `useQuery` within it's sub-tree:
1396
1397```js
1398import { ReactQueryConfigProvider } from 'react-query'
1399
1400const queryConfig = {
1401 retry: 3,
1402 retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000),
1403 staleTime: 0,
1404 cacheTime: 5 * 60 * 1000,
1405 refetchAllOnWindowFocus: true,
1406 refetchInterval: false,
1407 suspense: false,
1408}
1409
1410function App() {
1411 return (
1412 <ReactQueryConfigProvider config={queryConfig}>
1413 ...
1414 </ReactQueryConfigProvider>
1415 )
1416}
1417```
1418
1419### Options
1420
1421- `config: Object`
1422 - Must be **stable** or **memoized**. Do not create an inline object!
1423 - For a description of all config options, please see the [`useQuery` hook](#usequery).