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

README.md

1,222 lines43.8 KB

1![React Query Header](https://github.com/tannerlinsley/react-query/raw/master/media/header.png)
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 it's 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 - [Pagination](#pagination)
212 - [Load-More/Infinite-Scroll Pagination](#load-more-pagination)
213 - [Scroll Restoration](#scroll-restoration)
214 - [Manual Querying](#manual-querying)
215 - [Retries](#retries)
216 - [Retry Delay](#retry-delay)
217 - [Suspense Mode](#suspense-mode)
218- [Mutations](#mutations)
219 - [Basic Mutations](#basic-mutations)
220 - [Mutation Variables](#mutation-variables)
221 - [Invalidate and Refetch Queries from Mutations](#invalidate-and-refetch-queries-from-mutations)
222 - [Query Updates from Mutations](#query-updates-from-mutations)
223- [Manually or Optimistically Setting Query Data](#manually-or-optimistically-setting-query-data)
224- [Displaying Background Fetching Loading States](#displaying-background-fetching-loading-states)
225- [Displaying Global Background Fetching Loading State](#displaying-global-background-fetching-loading-state)
226- [Window-Focus Refetching](#window-focus-refetching)
227- [API](#api)
228 - [`useQuery`](#usequery)
229 - [`useMutation`](#usemutation)
230 - [`setQueryData`](#setquerydata)
231 - [`refetchQuery`](#refetchquery)
232 - [`refetchAllQueries`](#refetchallqueries)
233 - [`useIsFetching`](#useisfetching)
234 - [`useReactQueryConfig`](#usereactqueryconfig)
235​
236## Installation
237​
238```bash
239$ npm i --save react-query
240# or
241$ yarn add react-query
242```
243​
244## Queries
245​
246To make a new query, call the `useQuery` hook with:
247​
248- A **unique key for the query**
249- An **asynchronous function (or similar then-able)** to resolve the data
250​
251```js
252const info = useQuery('todos', fetchTodoList)
253```
254​
255The **unique key** you provide is used internally for refetching, caching, deduping related queries.
256​
257This key can be whatever you'd like it to be as long as:
258​
259- It changes when your query should be requested again
260- It is consistent across all instances of that specific query in your application
261​
262The query `info` returned contains all information about the query and can be easily destructured and used in your component:
263​
264```js
265function Todos() {
266 const { data, isLoading, error } = useQuery('todos', fetchTodoList)
267​
268 return (
269 <div>
270 {isLoading ? (
271 <span>Loading...</span>
272 ) : error ? (
273 <span>Error: {error.message}</span>
274 ) : data ? (
275 <ul>
276 {data.map(todo => (
277 <li key={todo.id}>{todo.title}</li>
278 ))}
279 </ul>
280 ) : null}
281 </div>
282 )
284```
285​
286### Query Keys
287​
288Since 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.
289​
290> Pro Tip: Variables passed in the key are automatically passed to your query function!
291​
292All of the following queries would result in using the same key:
293​
294```js
295useQuery(['todos', { status, page }])
296useQuery(['todos', { page, status }])
297useQuery(['todos', { page, status, other: undefined }])
298```
299​
300> Note: To aid you in your quest, if a query key is used that contains a `?` (like `todos?page=${page}&status=${status}`), you will see a gentle console warning to use the above format instead.
301​
302### Query Variables
303​
304To 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.
305​
306```js
307function Todos({ status }) {
308 const { data, isLoading, error } = useQuery(
309 ['todos', { status, page }],
310 fetchTodoList // This is the same as `fetchTodoList({ status, page })`
311 )
313```
314​
315Whenever a query's key changes, the query will automatically update:
316​
317```js
318function Todos() {
319 const [page, setPage] = useState(0)
320​
321 const { data, isLoading, error } = useQuery(
322 ['todos', { page }],
323 fetchTodoList
324 )
325​
326 const onNextPage = () => {
327 setPage(page => page + 1)
328 }
329​
330 return (
331 <>
332 {/* ... */}
333 <button onClick={onNextPage}>Load next page</button>
334 </>
335 )
337```
338​
339### Dependent Queries
340​
341React Query makes it easy to make queries that depends on other queries for both:
342​
343- Parallel Queries (avoiding waterfalls) and
344- Serial Queries (when a piece of data is required for the next query to happen.
345​
346To do this effectively, you can use the following 2 approaches:
347​
348#### Pass a falsey query key
349​
350If a query isn't ready to be requested yet, just pass a falsey value as the query key:
351​
352```js
353const { data: user } = useQuery(['user', { userId }])
354const { data: projects } = useQuery(user && ['projects', { userId: user.id }]) // User is `null`, so the query key will be falsey
355```
356​
357#### Use a query key function
358​
359If a function is passed, the query will not execute until the function can be called without throwing:
360​
361```js
362const { data: user } = useQuery(['user', { userId }])
363const { data: projects } = useQuery(() => ['projects', { userId: user.id }]) // This will throw until `user` is available
364```
365​
366#### Mix them together!
367​
368```js
369const [ready, setReady] = React.useState(false)
370const { data: user } = useQuery(ready && ['user', { userId }]) // Wait for ready
371const { data: projects } = useQuery(
372 () => ready && ['projects', { userId: user.id }] // Wait for ready and user.id
373```
374​
375### Caching & Invalidation
376​
377React Query caching is automatic out of the box. It uses a `stale-while-revalidate` in-memory caching model across queries along with query deduping to to always ensure a query's data is only stored once even if that query is used multiple times across your application.
378​
379At a glance:
380​
381- Caching is automatic and aggressive by default.
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 the query are mounted.
385- By default query results are **always** cached **when in use**.
386- If 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 time specified via the `cacheTime` option (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> **Did You Know?** - Because React Query doesn't use document normalization in its cache (made popular with libraries like Apollo and Redux-Query), it eliminates a whole range of common issues with caching like incorrect data merges, failed cache reads/writes, and imperative maintenance of the cache.
409​
410### Pagination
411​
412If all you need is page-based pagination, where the previous set of data is replaced with a new one, this section is not applicable to your use-case. For that, you can increment the page variable and pass it to your query via variables.
413​
414However, if your app needs to add more data to the list along with existing one (for example, infinite loading), React Query provides you with a way to fetch additional data without deleting the current data. Let's use page-based pagination for simplicity, but assume that we want to append new todo items at the end of the list.
415​
416```js
417function Todos() {
418 const { data, isLoading, error, refetch, isFetching } = useQuery(
419 ['todos', { page: 1 }],
420 fetchTodoList
421 )
422​
423 const onFetchMore = () => {
424 refetch({
425 variables: { page: data.pagination.nextPage },
426 merge: (prev, next) => ({
427 ...next,
428 // Merge the new todos with the existing ones
429 todos: [...prev.todos, ...next.todos],
430 }),
431 })
432 }
433​
434 return isLoading ? (
435 <span>Loading...</span>
436 ) : error ? (
437 <span>Error: {error.message}</span>
438 ) : data ? (
439 <>
440 <ul>
441 {data.todos.map(todo => (
442 <li key={todo.id}>{todo.title}</li>
443 ))}
444 </ul>
445 {data.pagination.hasMore && (
446 <button disabled={isFetching} onClick={onFetchMore}>
447 {isFetching ? 'Loading more todos...' : 'Load more todos'}
448 </button>
449 )}
450 </>
451 ) : null
453```
454​
455### Load-More/Infinite-Scroll Pagination
456​
457Rendering 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:
458​
459```js
460fetch('/api/projects?cursor=0'
461// { data: [...], nextId: 3}
462fetch('/api/projects?cursor=3'
463// { data: [...], nextId: 6}
464fetch('/api/projects?cursor=6'
465// { data: [...], nextId: 9}
466```
467​
468Using the `nextId` value in each page's response, we can configure `useQuery` to fetch more pages as needed:
469​
470- Configure your query function to use optional pagination variables. We'll send through the `nextId` as the `cursor` for the next page request
471- Set the `paginated` option to `true`
472- Define a `getCanFetchMore` option to know if there is more data to load (it receives the `lastPage` and `allPages` as parameters)
473​
474```js
475import { useQuery } from 'react-query'
476​
477function Todos() {
478 const {
479 data: pages,
480 isLoading,
481 isFetching,
482 isFetchingMore,
483 fetchMore,
484 canFetchMore,
485 } = useQuery(
486 'todos',
487 ({ nextId } = {}) => fetch('/api/projects?cursor=' + (nextId || 0)),
488 {
489 paginated: true,
490 getCanFetchMore: (lastPage, allPages) => next.nextId,
491 }
492 )
493​
494 // ...
496```
497​
498You'll notice a few new things now:
499​
500- `data` is now an array of pages that contain query results, instead of the query results themselves
501- A `fetchMore` function is now available
502- A `canFetchMore` boolean is now available
503- An `isFetchingMore` boolean is now available
504​
505These can now be used to render a "load more" list (this example uses an `offset` key):
506​
507```js
508import { useQuery } from 'react-query'
509​
510function Todos() {
511 const {
512 data: pages,
513 isLoading,
514 isFetching,
515 isFetchingMore,
516 fetchMore,
517 canFetchMore,
518 } = useQuery(
519 'projects',
520 ({ offset } = {}) => fetch('/api/projects?offset=' + (offset || 0)),
521 {
522 paginated: true,
523 getCanFetchMore: (lastPage, allPages) => next.nextId,
524 }
525 )
526​
527 const loadMore = async () => {
528 try {
529 // Get the last page
530 const lastPage = data[data.length - 1]
531 // Get the last item's ID
532 const lastItemId = lastPage[lastPage.length - 1].id
533 // Fetch more with the offset ID + 1
534 await fetchMore({
535 offset: lastItemId + 1,
536 })
537 } catch {}
538 }
539​
540 return isLoading ? (
541 <p>Loading...</p>
542 ) : data ? (
543 <>
544 {data.map((page, i) => (
545 <React.Fragment key={i}>
546 {page.data.map(project => (
547 <p key={project.id}>{project.name}</p>
548 ))}
549 </React.Fragment>
550 ))}
551 <div>
552 {canFetchMore ? (
553 <button onClick={loadMore} disabled={isFetchingMore}>
554 {isFetchingMore ? 'Loading more...' : 'Load More'}
555 </button>
556 ) : (
557 'Nothing more to fetch.'
558 )}
559 </div>
560 <div>
561 {isFetching && !isFetchingMore ? 'Background Updating...' : null}
562 </div>
563 </>
564 ) : null
566```
567​
568#### What happens when a paginated query needs to be refetched?\*\*
569​
570When 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.
571​
572### Scroll Restoration
573​
574Out 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.
575​
576### Manual Querying
577​
578If you ever want to disable a query from automatically running, you can use the `manual = true` option. When `manual` is set to true:
579​
580- The query will not automatically refetch due to changes to their query function or variables.
581- The query will not automatically refetch due to `refetchQueries` options in other queries or via `useRefetchQuery` calls.
582​
583```js
584function Todos() {
585 const { data, isLoading, error, refetch, isFetching } = useQuery(
586 'todos',
587 fetchTodoList,
588 {
589 manual: true,
590 }
591 )
592​
593 return (
594 <>
595 <button onClick={() => refetch()}>Fetch Todos</button>
596​
597 {isLoading ? (
598 <span>Loading...</span>
599 ) : error ? (
600 <span>Error: {error.message}</span>
601 ) : data ? (
602 <>
603 <ul>
604 {data.map(todo => (
605 <li key={todo.id}>{todo.title}</li>
606 ))}
607 </ul>
608 </>
609 ) : null}
610 </>
611 )
613```
614​
615> Pro Tip: Don't use `manual` for dependent queries. Use [Dependent Queries](#dependent-queries) instead!
616​
617### Retries
618​
619When 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`).
620​
621You can configure retries both on a global level and an individual query level.
622​
623- Setting `retry = false` will disable retries
624- Setting `retry = 6` will retry failing requests 6 times before showing the final error thrown by the function
625- Setting `retry = true` will infinitely retry failing requests.
626​
627```js
628import { useReactQueryConfig } from 'react-query'
629​
630// Turn off retries for all queries
631useReactQueryConfig({
632 retry: false,
633})
634​
635// Make specific query retry a certain number of times
636const { data, isLoading, error } = useQuery(
637 ['todos', { page: 1 }],
638 fetchTodoList,
639 {
640 retry: 10, // Will retry failed requests 10 times before displaying an error
641 }
643```
644​
645### Retry Delay
646​
647By 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.
648​
649The default `retryDelay` is set to double (starting at `1000`ms) with each attempt, but not exceed 30 seconds:
650​
651```js
652// Configure for all queries
653import { useReactQueryConfig } from 'react-query'
654​
655const config = {
656 retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000),
658​
659function App() {
660 useReactQueryConfig(config)
661​
662 return <Stuff />
664```
665​
666Though 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:
667​
668```js
669const { data, isLoading, error } = useQuery('todos', fetchTodoList, {
670 retryDelay: 10000, // Will always wait 1000ms to retry, regardless of how many retries
671})
672```
673​
674### Suspense Mode
675​
676React 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`:
677​
678```js
679const { useReactQueryConfig, useQuery } from 'react-query'
680​
681// Enable for all queries by default
682useReactQueryConfig({
683 suspense: true
684})
685​
686// Enable for an individual query
687useQuery(queryKey, queryFn, { suspense: true })
688```
689​
690When 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.
691​
692## Mutations
693​
694Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, React Query exports a `useMutation` hook.
695​
696### Basic Mutations
697​
698Assuming the server implements a ping mutation, that returns "pong" string, here's an example of the most basic mutation:
699​
700```js
701const PingPong = () => {
702 const [mutate, { data, isLoading, error }] = useMutation(pingMutation)
703​
704 const onPing = async () => {
705 try {
706 const data = await mutate()
707 console.log(data)
708 // { ping: 'pong' }
709 } catch {
710 // Uh oh, something went wrong
711 }
712 }
713 return <button onClick={onPing}>Ping</button>
715```
716​
717Mutations without variables are not that useful, so let's add some variables to closer match reality.
718​
719### Mutation Variables
720​
721To pass `variables` to your `mutate` function, call `mutate` with an object.
722​
723```js
724const CreateTodo = () => {
725 const [title, setTitle] = useState('')
726 const [mutate] = useMutation(createTodo)
727​
728 const onCreateTodo = async e => {
729 // Prevent the form from refreshing the page
730 e.preventDefault()
731​
732 try {
733 await mutate({ title })
734 // Todo was successfully created
735 } catch (error) {
736 // Uh oh, something went wrong
737 }
738 }
739​
740 return (
741 <form onSubmit={onCreateTodo}>
742 <input
743 type="text"
744 value={title}
745 onChange={e => setTitle(e.target.value)}
746 />
747 <br />
748 <button type="submit">Create Todo</button>
749 </form>
750 )
752```
753​
754Even with just variables, mutations aren't all that special, but when used with the `refetchQueries` and `updateQuery` options, they become a very powerful tool.
755​
756### Invalidate and Refetch Queries from Mutations
757​
758When 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.
759​
760For example, assume we have a mutation to post a new todo:
761​
762```js
763const [mutate] = useMutation(postTodo)
764```
765​
766When 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.
767​
768```js
769// When this mutation succeeds, any queries with the `todos` or `reminders` query key will be refetched
770mutate(newTodo, { refetchQueries: ['todos', 'reminders'], })
771​
772// The 3 queries below will be refetched when the mutation above succeeds
773const todoListQuery = useQuery('todos', fetchTodoList)
774const todoListQuery = useQuery(['todos', { page: 1 }, fetchTodoList)
775const remindersQuery = useQuery('reminders', fetchReminders)
776```
777​
778You can even refetch queries with specific variables by passing a query key tuple to `refetchQueries`:
779​
780```js
781mutate(newTodo, { refetchQueries: [['todos', { status: 'done' }]] })
782​
783// The query below will be refetched when the mutation above succeeds
784const todoListQuery = useQuery(['todos', { status: 'done' }], fetchTodoList)
785// However, the following query below will NOT be refetched
786const todoListQuery = useQuery('todos', fetchTodoList)
787```
788​
789If you want to **only** refetch `todos` queries that don't have variables, you can pass a tuple with `variables` set to `false`:
790​
791```js
792mutate(newTodo, { refetchQueries: [['todos', false]] })
793​
794// The query below will be refetched when the mutation above succeeds
795const todoListQuery = useQuery(['todos'], fetchTodoList)
796// However, the following query below will NOT be refetched
797const todoListQuery = useQuery(['todos', { status: 'done' }], fetchTodoList)
798```
799​
800If 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`:
801​
802```js
803const [mutate] = useMutation(addTodo, { refetchQueries: ['todos'] })
804​
805const run = async () => {
806 try {
807 await mutate(todo, { waitForRefetchQueries: true })
808 console.log('I will only log after all refetchQueries are done refetching!')
809 } catch {}
811```
812​
813It'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:
814​
815```js
816const [mutate] = useMutation(addTodo, { refetchQueries: ['todos'] })
817​
818const run = async () => {
819 try {
820 await mutate(todo, { refetchQueriesOnFailure: true })
821 // Even if the above mutation fails, any `todos` queries will still be refetched.
822 } catch {}
824```
825​
826### Query Updates from Mutations
827​
828When 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:
829​
830```js
831const [mutate] = useMutation(editTodo)
832​
833mutate(
834 {
835 id: 5,
836 name: 'Do the laundry',
837 },
838 {
839 updateQuery: ['todo', { id: 5 }],
840 }
842​
843// The query below will be updated with the response from the mutation above when it succeeds
844const { data, isLoading, error } = useQuery(['todo', { id: 5 }], fetchTodoByID)
845```
846​
847## Manually or Optimistically Setting Query Data
848​
849In 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:
850​
851```js
852import { setQueryData } from 'react-query'
853​
854// Full replacement
855setQueryData(['todo', { id: 5 }], newTodo)
856​
857// or functional update
858setQueryData(['todo', { id: 5 }], previous => ({ ...previous, status: 'done' }))
859```
860​
861**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.
862​
863Should you choose that you do _not_ want to refetch the query automatically, you can set the `shouldRefetch` option to `false`:
864​
865```js
866import { setQueryData } from 'react-query'
867​
868// Mutate, but do not automatically refetch the query in the background
869setQueryData(['todo', { id: 5 }], newTodo, {
870 shouldRefetch: false,
871})
872```
873​
874## Displaying Background Fetching Loading States
875​
876A 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:
877​
878```js
879function Todos() {
880 const { data: todos, isLoading, isFetching } = useQuery('todos', fetchTodos)
881​
882 return isLoading ? (
883 <span>Loading...</span>
884 ) : todos ? (
885 <>
886 {isFetching ? <div>Refreshing...</div> : null}
887​
888 <div>
889 {todos.map(todo => (
890 <Todo todo={todo} />
891 ))}
892 </div>
893 </>
894 ) : null
896```
897​
898## Displaying Global Background Fetching Loading State
899​
900In 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:
901​
902```js
903import { useIsFetching } from 'react-query'
904​
905function GlobalLoadingIndicator() {
906 const isFetching = useIsFetching()
907​
908 return isFetching ? (
909 <div>Queries are fetching in the background...</div>
910 ) : null
912```
913​
914## Window-Focus Refetching
915​
916If 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 `useReactQueryConfig`'s `refetchAllOnWindowFocus` option to disable it:
917​
918```js
919useReactQueryConfig({ refetchAllOnWindowFocus: false })
920```
921​
922# API
923​
924## `useQuery`
925​
926```js
927const {
928 data,
929 error,
930 isFetching,
931 isCached,
932 failureCount,
933 isLoading,
934 refetch,
935 // with pagination mode enabled
936 isFetchingMore,
937 canFetchMore,
938 fetchMore,
939} = useQuery(queryKey, queryFn, {
940 manual,
941 pagination,
942 getCanFetchMore,
943 staleTime,
944 retry,
945 retryDelay,
946 suspense,
947})
948```
949​
950### Options
951​
952- `queryKey: String | [String, Variables: Object] | falsey | Function => queryKey`
953 - **Required**
954 - The query key to use for this query.
955 - If a string is passed, it will be used as the query key
956 - If a `[String, Object]` tuple is passed, they will be serialized into a stable query key. See [Query Keys](#query-keys) for more information.
957 - If a falsey value is passed, the query will be disabled and not run automatically.
958 - 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.
959 - The query will automatically update when this key changes (if the key is not falsey and if `manual` is not set to `true`)
960 - `Variables: Object`
961 - If a tuple with variables is passed, this object should be **serializable**.
962 - Nested arrays and objects are supported
963 - The order of object keys is sorted to be stable before being serialized into the query key
964- `queryFn: Function(variables) => Promise(data/error)`
965 - **Required**
966 - The function that the query will use to request data
967 - Optionally receives the `variables` object passed from either the query key tuple (`useQuery(['todos', variables], queryFn)`) or the refetch method's `variables` option `refetch({ variables })`
968 - Must return a promise that will either resolves data or throws an error.
969- `pagination: Boolean`
970 - Set this to `true` to enable pagination mode
971 - In this mode, new pagination utilities are returned from `useQuery` and `data` becomes an array of page results
972- `manual: Boolean`
973 - Set this to `true` to disable automatic refetching when the query mounts or changes query keys.
974 - To refetch the query, use the `refetch` method returned from the `useQuery` instance.
975- `getCanFetchMore: Function(lastPage, allPages) => Boolean`
976 - **Required if using `pagination` mode**
977 - When using `pagination` mode, this function should return `true` if there is more data than can be fetched.
978- `retry: Boolean | Int`
979 - If `false`, failed queries will not retry by default
980 - If `true`, failed queries will retry infinitely
981 - If set to an `Int`, eg. `3`, failed queries will retry until the failed query count meets that number
982- `retryDelay: Function(retryAttempt: Int) => Int`
983 - This function receives a `retryAttempt` integer and returns the delay to apply before the next attempt in milliseconds
984 - A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff
985 - A function like `attempt => attempt * 1000` applies linear backoff.
986- `staleTime: Int`
987 - The time in milliseconds that cache data remains fresh. After a successful cache update, that cache data will become stale after this duration
988- `cacheTime: Int`
989 - 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.
990- `refetchInterval: false | Integer`
991 - Optional
992 - If set to a number, all queries will continuously refetch at this frequency in milliseconds
993- `suspense: Boolean`
994 - Optional
995 - Set this to `true` to enable suspense mode.
996 - When `true`, `useQuery` will suspend when `isLoading` would normally be `true`
997 - When `true`, `useQuery` will throw runtime errors when `error` would normally be truthy
998​
999### Returns
1000​
1001- `data: null | Any`
1002 - Defaults to `null`
1003 - The last successfully resolved data for the query.
1004- `error: null | Error`
1005 - The error object for the query, if an error was thrown.
1006- `isLoading: Boolean`
1007 - Will be `true` if the query is both fetching and does not have any cached data to display.
1008- `isFetching: Boolean`
1009 - Will be `true` if the query is currently fetching, including background fetching.
1010- `isCached: Boolean`
1011 - Will be `true` if the query's response is currently cached.
1012- `failureCount: Integer`
1013 - The failure count for the query.
1014 - Incremented every time the query fails.
1015 - Reset to `0` when the query succeeds.
1016- `refetch: Function({ variables: Object, merge: Function, disableThrow: Boolean })`
1017 - A function to manually refetch the query.
1018 - Supports custom variables (useful for "fetch more" calls)
1019 - Supports custom data merging (useful for "fetch more" calls)
1020 - Set `disableThrow` to true to disable this function from throwing if an error is encountered.
1021- `isFetchingMore: Boolean`
1022 - If using `pagination` mode, this will be `true` when fetching more results using the `fetchMore` function.
1023- `canFetchMore: Boolean`
1024 - If using `pagination` mode, this will be `true` if there is more data to be fetched (known via the required `getCanFetchMore` option function)
1025- `fetchMore: Function(variables) => Promise`
1026 - If using `pagination` mode, this function allows you to fetch the next "page" of results.
1027 - `variables` should be an object that is passed to your query function to retrieve the next page of results
1028​
1029## `useMutation`
1030​
1031```js
1032const [mutate, { data, isLoading, error }] = useMutation(mutationFn, {
1033 refetchQueries,
1034 refetchQueriesOnFailure,
1036​
1037const promise = mutate(variables, { updateQuery, waitForRefetchQueries })
1038```
1039​
1040### Options
1041​
1042- `mutationFn: Function(variables) => Promise`
1043 - **Required**
1044 - A function that performs an asynchronous task and returns a promise
1045- `refetchQueries: Array<QueryKey>`
1046 - Optional
1047 - When the mutation succeeds, these queries will be automatically refetched
1048 - Must be an array of query keys, eg. `['todos', ['todo', { id: 5 }], 'reminders']`
1049- `refetchQueriesOnFailure: Boolean`
1050 - Defaults to `false`
1051 - Set this to `true` if you want `refetchQueries` to be refetched regardless of the mutation succeeding.
1052- `variables: any`
1053 - Optional
1054 - The variables object to pass tot he `mutationFn`
1055- `updateQuery: QueryKey`
1056 - Optional
1057 - The query key for the individual query to update with the response from this mutation.
1058 - 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.
1059- `waitForRefetchQueries: Boolean`
1060 - Optional
1061 - If set to `true`, the promise returned by `mutate()` will not resolve until refetched queries are resolved as well.
1062​
1063### Returns
1064​
1065- `mutate: Function(variables, { updateQuery })`
1066 - The mutation function you can call with variables to trigger the mutation and optionally update a query with its response.
1067- `data: null | Any`
1068 - Defaults to `null`
1069 - The last successfully resolved data for the query.
1070- `error: null | Error`
1071 - The error object for the query, if an error was thrown.
1072- `isLoading: Boolean`
1073 - Will be `true` if the query is both fetching and does not have any cached data
1074- `promise: Promise`
1075 - The promise that is returned by the `mutationFn`
1076​
1077## `setQueryData`
1078​
1079`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.
1080​
1081```js
1082import { setQueryData } from 'react-query'
1083​
1084const maybePromise = setQueryData(queryKey, data, { shouldRefetch })
1085```
1086​
1087### Options
1088​
1089- `queryKey: QueryKey`
1090 - **Required**
1091 - The query key for the individual query to update with new data.
1092- `data: any | Function(old) => any`
1093 - **Required**
1094 - Must either be the new data or a function that receives the old data and returns the new data
1095- `shouldRefetch: Boolean`
1096 - Optional
1097 - Defaults to `true`
1098 - Set this to `false` to disable the automatic background refetch from happening
1099​
1100### Returns
1101​
1102- `maybePromise: undefined | Promise`
1103 - 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).
1104​
1105## `refetchQuery`
1106​
1107`refetchQuery` is a function for imperatively triggering a refetch of either:
1108​
1109- A group of queries
1110- A single query
1111​
1112By default, it will only refetch stale queries, but the `force` option can be used to refetch all queries, including non-stale ones.
1113​
1114```js
1115import { refetchQuery } from 'react-query'
1116​
1117const promise = refetchQuery(queryKey, { force })
1118```
1119​
1120### Options
1121​
1122- `queryKey: QueryKey`
1123 - **Required**
1124 - The query key for the query or query group to refetch.
1125 - 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' }]`).
1126 - 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)
1127 - 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' }]`)
1128- `force: Boolean`
1129 - Optional
1130 - Set this to true to force all queries to refetch instead of only stale ones.
1131​
1132### Returns
1133​
1134- `promise: Promise`
1135 - 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).
1136​
1137## `refetchAllQueries`
1138​
1139`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.
1140​
1141```js
1142import { refetchAllQueries } from 'react-query'
1143​
1144const promise = refetchAllQueries({ force, includeInactive })
1145```
1146​
1147### Options
1148​
1149- `force: Boolean`
1150 - Optional
1151 - Set this to `true` to force all queries to refetch instead of only stale ones.
1152- `includeInactive: Boolean`
1153 - Optional
1154 - Set this to `true` to also refetch inactive queries.
1155 - Overrides the `force` option to be `true`, regardless of it's value.
1156​
1157### Returns
1158​
1159- `promise: Promise`
1160 - 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).
1161​
1162## `useIsFetching`
1163​
1164`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)
1165​
1166```js
1167import { useIsFetching } from 'react-query'
1168​
1169const isFetching = useIsFetching()
1170```
1171​
1172### Returns
1173​
1174- `isFetching: Boolean`
1175 - Will be `true` if any query in your application is loading or fetching in the background
1176​
1177## `useReactQueryConfig`
1178​
1179`useReactQueryConfig` is optional and can be used to define defaults for all instances of `useQuery` through your app:
1180​
1181```js
1182import { useReactQueryConfig } from 'react-query'
1183​
1184useReactQueryConfig({
1185 retry: 3,
1186 retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000),
1187 staleTime: 0,
1188 cacheTime: 5 * 60 * 1000,
1189 refetchAllOnWindowFocus: true,
1190 refetchInterval: false,
1191 suspense: false,
1193```
1194​
1195### Options
1196​
1197For a description of all options, please see the [`useQuery` hook](#usequery).
1198​
1199### Returns
1200​
1201This hook does not return anything
1202​
1203### Example
1204​
1205```js
1206const config = {
1207 // These are the default config options for the useReactQueryConfig
1208 retry: 3,
1209 retryDelay: attempt =>
1210 Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000),
1211 staleTime: 10 * 1000, // 10 seconds
1212 invalidCacheTime: 10 * 1000, // 10 seconds
1214​
1215function App() {
1216 useReactQueryConfig({
1217 retry: 4
1218 })
1219​
1220 return </>
1222```