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 - [`clearQueryCache`](#clearquerycache)
238 - [`ReactQueryConfigProvider`](#reactqueryconfigprovider)
239
240## Installation
241
242```bash
243$ npm i --save react-query
244# or
245$ yarn add react-query
246```
247
248## Queries
249
250To make a new query, call the `useQuery` hook with:
251
252- A **unique key for the query**
253- An **asynchronous function (or similar then-able)** to resolve the data
254
255```js
256const info = useQuery('todos', fetchTodoList)
257```
258
259The **unique key** you provide is used internally for refetching, caching, deduping related queries.
260
261This key can be whatever you'd like it to be as long as:
262
263- It changes when your query should be requested again
264- It is consistent across all instances of that specific query in your application
265
266The query `info` returned contains all information about the query and can be easily destructured and used in your component:
267
268```js
269function Todos() {
270 const { data, isLoading, error } = useQuery('todos', fetchTodoList)
271
272 return (
273 <div>
274 {isLoading ? (
275 <span>Loading...</span>
276 ) : error ? (
277 <span>Error: {error.message}</span>
278 ) : data ? (
279 <ul>
280 {data.map(todo => (
281 <li key={todo.id}>{todo.title}</li>
282 ))}
283 </ul>
284 ) : null}
285 </div>
286 )
287}
288```
289
290### Query Keys
291
292Since 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.
293
294> Pro Tip: Variables passed in the key are automatically passed to your query function!
295
296All of the following queries would result in using the same key:
297
298```js
299useQuery(['todos', { status, page }])
300useQuery(['todos', { page, status }])
301useQuery(['todos', { page, status, other: undefined }])
302```
303
304### Query Variables
305
306To 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.
307
308```js
309function Todos({ status }) {
310 const { data, isLoading, error } = useQuery(
311 ['todos', { status, page }],
312 fetchTodoList // This is the same as `fetchTodoList({ status, page })`
313 )
314}
315```
316
317Whenever a query's key changes, the query will automatically update:
318
319```js
320function Todos() {
321 const [page, setPage] = useState(0)
322
323 const { data, isLoading, error } = useQuery(
324 ['todos', { page }],
325 fetchTodoList
326 )
327
328 const onNextPage = () => {
329 setPage(page => page + 1)
330 }
331
332 return (
333 <>
334 {/* ... */}
335 <button onClick={onNextPage}>Load next page</button>
336 </>
337 )
338}
339```
340
341### Dependent Queries
342
343React Query makes it easy to make queries that depend on other queries for both:
344
345- Parallel Queries (avoiding waterfalls) and
346- Serial Queries (when a piece of data is required for the next query to happen.
347
348To do this, you can use the following 2 approaches:
349
350#### Pass a falsey query key
351
352If a query isn't ready to be requested yet, just pass a falsey value as the query key:
353
354```js
355const { data: user } = useQuery(['user', { userId }])
356const { data: projects } = useQuery(user && ['projects', { userId: user.id }]) // User is `null`, so the query key will be falsey
357```
358
359#### Use a query key function
360
361If a function is passed, the query will not execute until the function can be called without throwing:
362
363```js
364const { data: user } = useQuery(['user', { userId }])
365const { data: projects } = useQuery(() => ['projects', { userId: user.id }]) // This will throw until `user` is available
366```
367
368#### Mix them together!
369
370```js
371const [ready, setReady] = React.useState(false)
372const { data: user } = useQuery(ready && ['user', { userId }]) // Wait for ready to be truthy
373const { data: projects } = useQuery(
374 () => ['projects', { userId: user.id }] // Wait for user.id to become available (and not throw)
375```
376
377### Caching & Invalidation
378
379React 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.
380
381At a glance:
382
383- The cache is keyed on unique `query + variables` combinations.
384- 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)
385- 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.
386- By default query results are **always** cached **when in use**.
387- 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
388- After a query is inactive for the `cacheTime` specified (defaults to 5 minutes), the query is deleted and garbage collected.
389
390<details>
391 <summary>A more detailed example of the caching lifecycle</summary>
392
393Let's assume we are using the default `cacheTime` of **5 minutes** and the default `staleTime` of `0`.
394
395- A new instance of `useQuery('todos', fetchTodos)` mounts
396 - 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.
397 - It will then cache the data using `'todos'` and `` as the unique identifiers for that cache.
398 - A stale invalidation is scheduled using the `staleTime` option as a delay (defaults to `0`, or immediately).
399- A second instance of `useQuery('todos', fetchTodos)` mounts elsewhere
400 - Because this exact data exist in the cache from the first instance of this query, that data is immediately returned from the cache
401 - Since the query is stale, it is refetched in the background automatically
402- Both instances of the `useQuery('todos', fetchTodos)` query are unmount and no longer in use.
403 - 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**).
404- No more instances of `useQuery('todos', fetchTodos)` appear within **5 minutes**
405 - This query and its data is deleted and garbage collected.
406
407</details>
408
409### Load-More & Infinite-Scroll Pagination
410
411Rendering 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:
412
413```js
414fetch('/api/projects?cursor=0'
415// { data: [...], nextId: 3}
416fetch('/api/projects?cursor=3'
417// { data: [...], nextId: 6}
418fetch('/api/projects?cursor=6'
419// { data: [...], nextId: 9}
420```
421
422Using the `nextId` value in each page's response, we can configure `useQuery` to fetch more pages as needed:
423
424- Configure your query function to use optional pagination variables. We'll send through the `nextId` as the `cursor` for the next page request
425- Set the `paginated` option to `true`
426- Define a `getCanFetchMore` option to know if there is more data to load (it receives the `lastPage` and `allPages` as parameters)
427
428```js
429import { useQuery } from 'react-query'
430
431function Todos() {
432 const {
433 data: pages,
434 isLoading,
435 isFetching,
436 isFetchingMore,
437 fetchMore,
438 canFetchMore,
439 } = useQuery(
440 'todos',
441 ({ nextId } = {}) => fetch('/api/projects?cursor=' + (nextId || 0)),
442 {
443 paginated: true,
444 getCanFetchMore: (lastPage, allPages) => lastPage.nextId,
445 }
446 )
447
448 // ...
449}
450```
451
452You'll notice a few new things now:
453
454- `data` is now an array of pages that contain query results, instead of the query results themselves
455- A `fetchMore` function is now available
456- A `canFetchMore` boolean is now available
457- An `isFetchingMore` boolean is now available
458
459These can now be used to render a "load more" list (this example uses an `offset` key):
460
461```js
462import { useQuery } from 'react-query'
463
464function Todos() {
465 const {
466 data: pages,
467 isLoading,
468 isFetching,
469 isFetchingMore,
470 fetchMore,
471 canFetchMore,
472 } = useQuery(
473 'projects',
474 ({ offset } = {}) => fetch('/api/projects?offset=' + (offset || 0)),
475 {
476 paginated: true,
477 getCanFetchMore: (lastPage, allPages) => lastPage.nextId,
478 }
479 )
480
481 const loadMore = async () => {
482 try {
483 // Get the last page
484 const lastPage = pages[pages.length - 1]
485 // Get the last item's ID
486 const lastItemId = lastPage[lastPage.length - 1].id
487 // Fetch more with the offset ID + 1
488 await fetchMore({
489 offset: lastItemId + 1,
490 })
491 } catch {}
492 }
493
494 return isLoading ? (
495 <p>Loading...</p>
496 ) : data ? (
497 <>
498 {data.map((page, i) => (
499 <React.Fragment key={i}>
500 {page.data.map(project => (
501 <p key={project.id}>{project.name}</p>
502 ))}
503 </React.Fragment>
504 ))}
505 <div>
506 {canFetchMore ? (
507 <button onClick={loadMore} disabled={isFetchingMore}>
508 {isFetchingMore ? 'Loading more...' : 'Load More'}
509 </button>
510 ) : (
511 'Nothing more to fetch.'
512 )}
513 </div>
514 <div>
515 {isFetching && !isFetchingMore ? 'Background Updating...' : null}
516 </div>
517 </>
518 ) : null
519}
520```
521
522#### What happens when a paginated query needs to be refetched?\*\*
523
524When 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.
525
526### Scroll Restoration
527
528Out 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.
529
530### Manual Querying
531
532If you ever want to disable a query from automatically running, you can use the `manual = true` option. When `manual` is set to true:
533
534- The query will not automatically refetch due to changes to their query function or variables.
535- The query will not automatically refetch due to `refetchQueries` options in other queries or via `refetchQuery` calls.
536
537```js
538function Todos() {
539 const { data, isLoading, error, refetch, isFetching } = useQuery(
540 'todos',
541 fetchTodoList,
542 {
543 manual: true,
544 }
545 )
546
547 return (
548 <>
549 <button onClick={() => refetch()}>Fetch Todos</button>
550
551 {isLoading ? (
552 <span>Loading...</span>
553 ) : error ? (
554 <span>Error: {error.message}</span>
555 ) : data ? (
556 <>
557 <ul>
558 {data.map(todo => (
559 <li key={todo.id}>{todo.title}</li>
560 ))}
561 </ul>
562 </>
563 ) : null}
564 </>
565 )
566}
567```
568
569> Pro Tip: Don't use `manual` for dependent queries. Use [Dependent Queries](#dependent-queries) instead!
570
571### Retries
572
573When 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`).
574
575You can configure retries both on a global level and an individual query level.
576
577- Setting `retry = false` will disable retries
578- Setting `retry = 6` will retry failing requests 6 times before showing the final error thrown by the function
579- Setting `retry = true` will infinitely retry failing requests.
580
581```js
582import { useQuery } from 'react-query'
583
584// Make specific query retry a certain number of times
585const { data, isLoading, error } = useQuery(
586 ['todos', { page: 1 }],
587 fetchTodoList,
588 {
589 retry: 10, // Will retry failed requests 10 times before displaying an error
590 }
591)
592```
593
594### Retry Delay
595
596By 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.
597
598The default `retryDelay` is set to double (starting at `1000`ms) with each attempt, but not exceed 30 seconds:
599
600```js
601// Configure for all queries
602import { ReactQueryConfigProvider } from 'react-query'
603
604const queryConfig = {
605 retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000),
606}
607
608function App() {
609 return (
610 <ReactQueryConfigProvider config={queryConfig}>
611 ...
612 </ReactQueryConfigProvider>
613 )
614}
615```
616
617Though 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:
618
619```js
620const { data, isLoading, error } = useQuery('todos', fetchTodoList, {
621 retryDelay: 10000, // Will always wait 1000ms to retry, regardless of how many retries
622})
623```
624
625### Prefetching
626
627If 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:
628
629```js
630import { prefetchQuery } from 'react-query'
631
632const prefetchTodos async () => {
633 const queryData = await prefetchQuery('todos', () => fetch('/todos'))
634 // The results of this query will be cached like a normal query
635}
636```
637
638The 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`.
639
640### Suspense Mode
641
642React 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`.
643
644Global configuration:
645
646```js
647// Configure for all queries
648import { ReactQueryConfigProvider } from 'react-query'
649
650const queryConfig = {
651 suspense: true,
652}
653
654function App() {
655 return (
656 <ReactQueryConfigProvider config={queryConfig}>
657 ...
658 </ReactQueryConfigProvider>
659 )
660}
661```
662
663Query configuration:
664
665```js
666const { useQuery } from 'react-query'
667
668// Enable for an individual query
669useQuery(queryKey, queryFn, { suspense: true })
670```
671
672When 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.
673
674#### Fetch-on-render vs Fetch-as-you-render
675
676Out 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.
677
678## Mutations
679
680Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, React Query exports a `useMutation` hook.
681
682### Basic Mutations
683
684Assuming the server implements a ping mutation, that returns "pong" string, here's an example of the most basic mutation:
685
686```js
687const PingPong = () => {
688 const [mutate, { data, isLoading, error }] = useMutation(pingMutation)
689
690 const onPing = async () => {
691 try {
692 const data = await mutate()
693 console.log(data)
694 // { ping: 'pong' }
695 } catch {
696 // Uh oh, something went wrong
697 }
698 }
699 return <button onClick={onPing}>Ping</button>
700}
701```
702
703Mutations without variables are not that useful, so let's add some variables to closer match reality.
704
705### Mutation Variables
706
707To pass `variables` to your `mutate` function, call `mutate` with an object.
708
709```js
710const CreateTodo = () => {
711 const [title, setTitle] = useState('')
712 const [mutate] = useMutation(createTodo)
713
714 const onCreateTodo = async e => {
715 // Prevent the form from refreshing the page
716 e.preventDefault()
717
718 try {
719 await mutate({ title })
720 // Todo was successfully created
721 } catch (error) {
722 // Uh oh, something went wrong
723 }
724 }
725
726 return (
727 <form onSubmit={onCreateTodo}>
728 <input
729 type="text"
730 value={title}
731 onChange={e => setTitle(e.target.value)}
732 />
733 <br />
734 <button type="submit">Create Todo</button>
735 </form>
736 )
737}
738```
739
740Even with just variables, mutations aren't all that special, but when used with the `refetchQueries` and `updateQuery` options, they become a very powerful tool.
741
742### Invalidate and Refetch Queries from Mutations
743
744When 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.
745
746For example, assume we have a mutation to post a new todo:
747
748```js
749const [mutate] = useMutation(postTodo)
750```
751
752When 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.
753
754```js
755// When this mutation succeeds, any queries with the `todos` or `reminders` query key will be refetched
756mutate(newTodo, { refetchQueries: ['todos', 'reminders'], })
757
758// The 3 queries below will be refetched when the mutation above succeeds
759const todoListQuery = useQuery('todos', fetchTodoList)
760const todoListQuery = useQuery(['todos', { page: 1 }, fetchTodoList)
761const remindersQuery = useQuery('reminders', fetchReminders)
762```
763
764You can even refetch queries with specific variables by passing a query key tuple to `refetchQueries`:
765
766```js
767mutate(newTodo, { refetchQueries: [['todos', { status: 'done' }]] })
768
769// The query below will be refetched when the mutation above succeeds
770const todoListQuery = useQuery(['todos', { status: 'done' }], fetchTodoList)
771// However, the following query below will NOT be refetched
772const todoListQuery = useQuery('todos', fetchTodoList)
773```
774
775If you want to **only** refetch `todos` queries that don't have variables, you can pass a tuple with `variables` set to `false`:
776
777```js
778mutate(newTodo, { refetchQueries: [['todos', false]] })
779
780// The query below will be refetched when the mutation above succeeds
781const todoListQuery = useQuery(['todos'], fetchTodoList)
782// However, the following query below will NOT be refetched
783const todoListQuery = useQuery(['todos', { status: 'done' }], fetchTodoList)
784```
785
786If 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`:
787
788```js
789const [mutate] = useMutation(addTodo, { refetchQueries: ['todos'] })
790
791const run = async () => {
792 try {
793 await mutate(todo, { waitForRefetchQueries: true })
794 console.log('I will only log after all refetchQueries are done refetching!')
795 } catch {}
796}
797```
798
799It'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:
800
801```js
802const [mutate] = useMutation(addTodo, { refetchQueries: ['todos'] })
803
804const run = async () => {
805 try {
806 await mutate(todo, { refetchQueriesOnFailure: true })
807 // Even if the above mutation fails, any `todos` queries will still be refetched.
808 } catch {}
809}
810```
811
812### Query Updates from Mutations
813
814When 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:
815
816```js
817const [mutate] = useMutation(editTodo)
818
819mutate(
820 {
821 id: 5,
822 name: 'Do the laundry',
823 },
824 {
825 updateQuery: ['todo', { id: 5 }],
826 }
827)
828
829// The query below will be updated with the response from the mutation above when it succeeds
830const { data, isLoading, error } = useQuery(['todo', { id: 5 }], fetchTodoByID)
831```
832
833## Manually or Optimistically Setting Query Data
834
835In 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:
836
837```js
838import { setQueryData } from 'react-query'
839
840// Full replacement
841setQueryData(['todo', { id: 5 }], newTodo)
842
843// or functional update
844setQueryData(['todo', { id: 5 }], previous => ({ ...previous, status: 'done' }))
845```
846
847**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.
848
849Should you choose that you do _not_ want to refetch the query automatically, you can set the `shouldRefetch` option to `false`:
850
851```js
852import { setQueryData } from 'react-query'
853
854// Mutate, but do not automatically refetch the query in the background
855setQueryData(['todo', { id: 5 }], newTodo, {
856 shouldRefetch: false,
857})
858```
859
860## Displaying Background Fetching Loading States
861
862A 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:
863
864```js
865function Todos() {
866 const { data: todos, isLoading, isFetching } = useQuery('todos', fetchTodos)
867
868 return isLoading ? (
869 <span>Loading...</span>
870 ) : todos ? (
871 <>
872 {isFetching ? <div>Refreshing...</div> : null}
873
874 <div>
875 {todos.map(todo => (
876 <Todo todo={todo} />
877 ))}
878 </div>
879 </>
880 ) : null
881}
882```
883
884## Displaying Global Background Fetching Loading State
885
886In 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:
887
888```js
889import { useIsFetching } from 'react-query'
890
891function GlobalLoadingIndicator() {
892 const isFetching = useIsFetching()
893
894 return isFetching ? (
895 <div>Queries are fetching in the background...</div>
896 ) : null
897}
898```
899
900## Window-Focus Refetching
901
902If 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:
903
904```js
905const queryConfig = { refetchAllOnWindowFocus: false }
906
907function App() {
908 return (
909 <ReactQueryConfigProvider config={queryConfig}>
910 ...
911 </ReactQueryConfigProvider>
912 )
913}
914```
915
916## Custom Query Key Serializers (Experimental)
917
918> **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
919
920If 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:
921
922```js
923const queryConfig = {
924 queryKeySerializerFn: userQueryKey => {
925 // Your custom logic here...
926
927 return [fullQueryHash, queryGroupId, variablesHash, variables]
928 },
929}
930
931function App() {
932 return (
933 <ReactQueryConfigProvider config={queryConfig}>
934 ...
935 </ReactQueryConfigProvider>
936 )
937}
938```
939
940- `userQueryKey: any`
941 - This is the queryKey passed in `useQuery` and all other public methods and utilities exported by React Query.
942- `fullQueryHash: string`
943 - This must be a unique `string` representing the query and variables.
944 - It must be stable and deterministic and should not change if things like the order of variables is changed or shuffled.
945- `queryGroupId: string`
946 - This must be a unique `string` representing only the query type without any variables
947 - It must be stable and deterministic and should not change if the variables of the query change
948- `variablesHash: string`
949 - This must be a unique `string` representing only the variables of the query
950 - It must be stable and deterministic and should not change if things like the order of variables is changed or shuffled.
951- `variables: any`
952 - This is the object that will be passed to the `queryFn` when using `useQuery`.
953
954> An additional `stableStringify` utility is also exported to help with stringifying objects to have sorted keys.
955
956#### URL Query Key Serializer Example
957
958The example below shows how to build your own serializer for use with urls and use it with React Query:
959
960```js
961import { ReactQueryConfigProvider, stableStringify } from 'react-query'
962
963function urlQueryKeySerializer(queryKey) {
964 // Deconstruct the url
965 let [url, params = ''] = queryKey.split('?')
966
967 // Build the variables object
968 let variables = {}
969 params
970 .split('&')
971 .filter(Boolean)
972 .forEach(param => {
973 const [key, value] = param.split('=')
974 variables[key] = value
975 })
976
977 // Use stableStringify to turn variables into a stable string
978 const variablesHash = Object.keys(variables).length
979 ? stableStringify(variables)
980 : ''
981
982 // Remove trailing slashes from the url to make an ID
983 const queryGroupId = url.replace(/\/{1,}$/, '')
984
985 const queryHash = `${id}_${variablesHash}`
986
987 return [queryHash, queryGroupId, variablesHash, variables]
988}
989
990const queryConfig = {
991 queryKeySerializerFn: urlQueryKeySerializer,
992}
993
994function App() {
995 return (
996 <ReactQueryConfigProvider config={queryConfig}>
997 ...
998 </ReactQueryConfigProvider>
999 )
1000}
1001
1002// Heck, you can even make your own custom useQueryHook!
1003
1004function useUrlQuery(url, options) {
1005 return useQuery(url, () => axios.get(url).then(res => res.data))
1006}
1007
1008// Use it in your app!
1009
1010function Todos() {
1011 const todosQuery = useUrlQuery(`/todos`)
1012}
1013
1014function FilteredTodos({ status = 'pending' }) {
1015 const todosQuery = useFunctionQuery([getTodos, { status }])
1016}
1017
1018function Todo({ id }) {
1019 const todoQuery = useUrlQuery(`/todos/${id}`)
1020}
1021
1022refetchQuery('/todos')
1023refetchQuery('/todos?status=pending')
1024refetchQuery('/todos/5')
1025```
1026
1027#### Function Query Key Serializer Example
1028
1029The example below shows how to you build your own functional serializer and use it with React Query:
1030
1031```js
1032import { ReactQueryConfigProvider, stableStringify } from 'react-query'
1033
1034// A map to keep track of our function pointers
1035const functionSerializerMap = new Map()
1036
1037function functionQueryKeySerializer(queryKey) {
1038 if (!queryKey) {
1039 return []
1040 }
1041
1042 let queryFn = queryKey
1043 let variables
1044
1045 if (Array.isArray(queryKey)) {
1046 queryFn = queryKey[0]
1047 variables = queryKey[1]
1048 }
1049
1050 // Get or create an ID for the function pointer
1051 const queryGroupId = functionSerializerMap.get(queryFn) || (() => {
1052 const id = Date.now()
1053 functionSerializerMap.set(queryFn, id)
1054 return id
1055 })()
1056
1057 const variablesIsObject = isObject(variables)
1058
1059 const variablesHash = variablesIsObject ? stableStringify(variables) : ''
1060
1061 const queryHash = `${queryGroupId}_${variablesHash}`
1062
1063 return [
1064 queryHash,
1065 queryGroupId,
1066 variablesHash,
1067 variables,
1068 ]
1069}
1070
1071const queryConfig = {
1072 queryKeySerializerFn: functionQueryKeySerializer,
1073}
1074
1075function App() {
1076 return (
1077 <ReactQueryConfigProvider config={queryConfig}>
1078 ...
1079 </ReactQueryConfigProvider>
1080 )
1081}
1082// Heck, you can even make your own custom useQueryHook!
1083
1084function useFunctionQuery(functionTuple, options) {
1085 const [queryFn, variables] = Array.isArray(functionTuple) ? functionTuple : [functionTuple]
1086 return useQuery(functionTuple, queryFn, options)
1087}
1088
1089// Use it in your app!
1090
1091function Todos() {
1092 const todosQuery = useFunctionQuery(getTodos)
1093}
1094
1095function FilteredTodos({ status = 'pending' }) {
1096 const todosQuery = useFunctionQuery([getTodos, { status }])
1097}
1098
1099function Todo({ id }) {
1100 const todoQuery = useFunctionQuery([getTodo, { id }])
1101}
1102
1103refetchQuery(getTodos)
1104refetchQuery([getTodos, { status: 'pending' }])
1105refetchQuery([getTodo, { id: 5}])
1106```
1107
1108# API
1109
1110## `useQuery`
1111
1112```js
1113const {
1114 data,
1115 error,
1116 isFetching,
1117 isCached,
1118 failureCount,
1119 isLoading,
1120 refetch,
1121 // with paginated mode enabled
1122 isFetchingMore,
1123 canFetchMore,
1124 fetchMore,
1125} = useQuery(queryKey, queryFn, {
1126 manual,
1127 paginated,
1128 getCanFetchMore,
1129 staleTime,
1130 retry,
1131 retryDelay,
1132 onSuccess,
1133 onError,
1134 suspense,
1135})
1136```
1137
1138### Options
1139
1140- `queryKey: String | [String, Variables: Object] | falsey | Function => queryKey`
1141 - **Required**
1142 - The query key to use for this query.
1143 - If a string is passed, it will be used as the query key
1144 - If a `[String, Object]` tuple is passed, they will be serialized into a stable query key. See [Query Keys](#query-keys) for more information.
1145 - If a falsey value is passed, the query will be disabled and not run automatically.
1146 - 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.
1147 - The query will automatically update when this key changes (if the key is not falsey and if `manual` is not set to `true`)
1148 - `Variables: Object`
1149 - If a tuple with variables is passed, this object should be **serializable**.
1150 - Nested arrays and objects are supported
1151 - The order of object keys is sorted to be stable before being serialized into the query key
1152- `queryFn: Function(variables) => Promise(data/error)`
1153 - **Required**
1154 - The function that the query will use to request data
1155 - 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 })`
1156 - Must return a promise that will either resolves data or throws an error.
1157- `paginated: Boolean`
1158 - Set this to `true` to enable `paginated` mode
1159 - In this mode, new pagination utilities are returned from `useQuery` and `data` becomes an array of page results
1160- `manual: Boolean`
1161 - Set this to `true` to disable automatic refetching when the query mounts or changes query keys.
1162 - To refetch the query, use the `refetch` method returned from the `useQuery` instance.
1163- `getCanFetchMore: Function(lastPage, allPages) => Boolean`
1164 - **Required if using `paginated` mode**
1165 - When using `paginated` mode, this function should return `true` if there is more data than can be fetched.
1166- `retry: Boolean | Int`
1167 - If `false`, failed queries will not retry by default
1168 - If `true`, failed queries will retry infinitely
1169 - If set to an `Int`, eg. `3`, failed queries will retry until the failed query count meets that number
1170- `retryDelay: Function(retryAttempt: Int) => Int`
1171 - This function receives a `retryAttempt` integer and returns the delay to apply before the next attempt in milliseconds
1172 - A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff
1173 - A function like `attempt => attempt * 1000` applies linear backoff.
1174- `staleTime: Int`
1175 - The time in milliseconds that cache data remains fresh. After a successful cache update, that cache data will become stale after this duration
1176- `cacheTime: Int`
1177 - 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.
1178- `refetchInterval: false | Integer`
1179 - Optional
1180 - If set to a number, all queries will continuously refetch at this frequency in milliseconds
1181- `onError: Function(err) => void`
1182 - Optional
1183 - This function will fire if the query encounters an error (after all retries have happened) and will be passed the error.
1184- `onSucess: Function(data) => data`
1185 - Optional
1186 - This function will fire any time the query successfully fetches new data.
1187- `suspense: Boolean`
1188 - Optional
1189 - Set this to `true` to enable suspense mode.
1190 - When `true`, `useQuery` will suspend when `isLoading` would normally be `true`
1191 - When `true`, `useQuery` will throw runtime errors when `error` would normally be truthy
1192
1193### Returns
1194
1195- `data: null | Any`
1196 - Defaults to `null`
1197 - The last successfully resolved data for the query.
1198- `error: null | Error`
1199 - The error object for the query, if an error was thrown.
1200- `isLoading: Boolean`
1201 - Will be `true` if the query is both fetching and does not have any cached data to display.
1202- `isFetching: Boolean`
1203 - Will be `true` if the query is currently fetching, including background fetching.
1204- `isCached: Boolean`
1205 - Will be `true` if the query's response is currently cached.
1206- `failureCount: Integer`
1207 - The failure count for the query.
1208 - Incremented every time the query fails.
1209 - Reset to `0` when the query succeeds.
1210- `refetch: Function({ variables: Object, merge: Function, disableThrow: Boolean })`
1211 - A function to manually refetch the query.
1212 - Supports custom variables (useful for "fetch more" calls)
1213 - Supports custom data merging (useful for "fetch more" calls)
1214 - Set `disableThrow` to true to disable this function from throwing if an error is encountered.
1215- `isFetchingMore: Boolean`
1216 - If using `paginated` mode, this will be `true` when fetching more results using the `fetchMore` function.
1217- `canFetchMore: Boolean`
1218 - If using `paginated` mode, this will be `true` if there is more data to be fetched (known via the required `getCanFetchMore` option function)
1219- `fetchMore: Function(variables) => Promise`
1220 - If using `paginated` mode, this function allows you to fetch the next "page" of results.
1221 - `variables` should be an object that is passed to your query function to retrieve the next page of results
1222
1223## `useMutation`
1224
1225```js
1226const [mutate, { data, isLoading, error }] = useMutation(mutationFn, {
1227 refetchQueries,
1228 refetchQueriesOnFailure,
1229})
1230
1231const promise = mutate(variables, { updateQuery, waitForRefetchQueries })
1232```
1233
1234### Options
1235
1236- `mutationFn: Function(variables) => Promise`
1237 - **Required**
1238 - A function that performs an asynchronous task and returns a promise
1239- `refetchQueries: Array<QueryKey>`
1240 - Optional
1241 - When the mutation succeeds, these queries will be automatically refetched
1242 - Must be an array of query keys, eg. `['todos', ['todo', { id: 5 }], 'reminders']`
1243- `refetchQueriesOnFailure: Boolean`
1244 - Defaults to `false`
1245 - Set this to `true` if you want `refetchQueries` to be refetched regardless of the mutation succeeding.
1246- `variables: any`
1247 - Optional
1248 - The variables object to pass tot he `mutationFn`
1249- `updateQuery: QueryKey`
1250 - Optional
1251 - The query key for the individual query to update with the response from this mutation.
1252 - 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.
1253- `waitForRefetchQueries: Boolean`
1254 - Optional
1255 - If set to `true`, the promise returned by `mutate()` will not resolve until refetched queries are resolved as well.
1256
1257### Returns
1258
1259- `mutate: Function(variables, { updateQuery })`
1260 - The mutation function you can call with variables to trigger the mutation and optionally update a query with its response.
1261- `data: null | Any`
1262 - Defaults to `null`
1263 - The last successfully resolved data for the query.
1264- `error: null | Error`
1265 - The error object for the query, if an error was thrown.
1266- `isLoading: Boolean`
1267 - Will be `true` if the query is both fetching and does not have any cached data
1268- `promise: Promise`
1269 - The promise that is returned by the `mutationFn`
1270
1271## `setQueryData`
1272
1273`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.
1274
1275```js
1276import { setQueryData } from 'react-query'
1277
1278const maybePromise = setQueryData(queryKey, data, { shouldRefetch })
1279```
1280
1281### Options
1282
1283- `queryKey: QueryKey`
1284 - **Required**
1285 - The query key for the individual query to update with new data.
1286- `data: any | Function(old) => any`
1287 - **Required**
1288 - Must either be the new data or a function that receives the old data and returns the new data
1289- `shouldRefetch: Boolean`
1290 - Optional
1291 - Defaults to `true`
1292 - Set this to `false` to disable the automatic background refetch from happening
1293
1294### Returns
1295
1296- `maybePromise: undefined | Promise`
1297 - 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).
1298
1299## `refetchQuery`
1300
1301`refetchQuery` is a function that can ge used to trigger a refetch of
1302
1303- A group of active queries
1304- A single, specific query
1305
1306By default, `refetchQuery` will only refetch stale queries, but the `force` option can be used to include non-stale ones.
1307
1308```js
1309import { refetchQuery } from 'react-query'
1310
1311const promise = refetchQuery(queryKey, { force })
1312```
1313
1314### Options
1315
1316- `queryKey: QueryKey`
1317 - **Required**
1318 - The query key for the query or query group to refetch.
1319 - 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' }]`).
1320 - 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)
1321 - 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' }]`)
1322- `force: Boolean`
1323 - Optional
1324 - Set this to true to force all queries to refetch instead of only stale ones.
1325
1326### Returns
1327
1328- `promise: Promise`
1329 - 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).
1330
1331## `refetchAllQueries`
1332
1333`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.
1334
1335```js
1336import { refetchAllQueries } from 'react-query'
1337
1338const promise = refetchAllQueries({ force, includeInactive })
1339```
1340
1341### Options
1342
1343- `force: Boolean`
1344 - Optional
1345 - Set this to `true` to force all queries to refetch instead of only stale ones.
1346- `includeInactive: Boolean`
1347 - Optional
1348 - Set this to `true` to also refetch inactive queries.
1349 - Overrides the `force` option to be `true`, regardless of it's value.
1350
1351### Returns
1352
1353- `promise: Promise`
1354 - 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).
1355
1356## `useIsFetching`
1357
1358`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)
1359
1360```js
1361import { useIsFetching } from 'react-query'
1362
1363const isFetching = useIsFetching()
1364```
1365
1366### Returns
1367
1368- `isFetching: Boolean`
1369 - Will be `true` if any query in your application is loading or fetching in the background
1370
1371## `prefetchQuery`
1372
1373`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:
1374
1375```js
1376import { prefetchQuery } from 'react-query'
1377
1378const data = await prefetchQuery(queryKey, queryFn, { force, ...config })
1379```
1380
1381### Options
1382
1383The options for `prefetchQuery` are exactly the same as those of [`useQuery`](#usequery), with the exception of a `force` option:
1384
1385- `force: Boolean`
1386 - Optional
1387 - Set this to true to prefetch a query **even if it is stale**
1388
1389### Returns
1390
1391- `promise: Promise`
1392 - A promise is returned that will either resolve with the **query's response data**, or throw with an **error**.
1393
1394## `clearQueryCache`
1395
1396`clearQueryCache` does exactly what it sounds like, it clears all query caches. It does this by:
1397
1398- Immediately deleting any queries that no not have active subscriptions
1399- Immediately setting `data` to `null` for all queries with active subscriptions
1400
1401```js
1402import { clearQueryCache } from 'react-query'
1403
1404clearQueryCache()
1405```
1406
1407## `ReactQueryConfigProvider`
1408
1409`ReactQueryConfigProvider` is an optional provider component and can be used to define defaults for all instances of `useQuery` within it's sub-tree:
1410
1411```js
1412import { ReactQueryConfigProvider } from 'react-query'
1413
1414const queryConfig = {
1415 retry: 3,
1416 retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000),
1417 staleTime: 0,
1418 cacheTime: 5 * 60 * 1000,
1419 refetchAllOnWindowFocus: true,
1420 refetchInterval: false,
1421 suspense: false,
1422}
1423
1424function App() {
1425 return (
1426 <ReactQueryConfigProvider config={queryConfig}>
1427 ...
1428 </ReactQueryConfigProvider>
1429 )
1430}
1431```
1432
1433### Options
1434
1435- `config: Object`
1436 - Must be **stable** or **memoized**. Do not create an inline object!
1437 - For a description of all config options, please see the [`useQuery` hook](#usequery).