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

README.md

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