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

README.md

1,370 lines47.4 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 - [`ReactQueryConfigProvider`](#reactqueryconfigprovider)
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### Load-More & Infinite-Scroll Pagination
406​
407Rendering 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:
408​
409```js
410fetch('/api/projects?cursor=0'
411// { data: [...], nextId: 3}
412fetch('/api/projects?cursor=3'
413// { data: [...], nextId: 6}
414fetch('/api/projects?cursor=6'
415// { data: [...], nextId: 9}
416```
417​
418Using the `nextId` value in each page's response, we can configure `useQuery` to fetch more pages as needed:
419​
420- Configure your query function to use optional pagination variables. We'll send through the `nextId` as the `cursor` for the next page request
421- Set the `paginated` option to `true`
422- Define a `getCanFetchMore` option to know if there is more data to load (it receives the `lastPage` and `allPages` as parameters)
423​
424```js
425import { useQuery } from 'react-query'
426​
427function Todos() {
428 const {
429 data: pages,
430 isLoading,
431 isFetching,
432 isFetchingMore,
433 fetchMore,
434 canFetchMore,
435 } = useQuery(
436 'todos',
437 ({ nextId } = {}) => fetch('/api/projects?cursor=' + (nextId || 0)),
438 {
439 paginated: true,
440 getCanFetchMore: (lastPage, allPages) => next.nextId,
441 }
442 )
443​
444 // ...
446```
447​
448You'll notice a few new things now:
449​
450- `data` is now an array of pages that contain query results, instead of the query results themselves
451- A `fetchMore` function is now available
452- A `canFetchMore` boolean is now available
453- An `isFetchingMore` boolean is now available
454​
455These can now be used to render a "load more" list (this example uses an `offset` key):
456​
457```js
458import { useQuery } from 'react-query'
459​
460function Todos() {
461 const {
462 data: pages,
463 isLoading,
464 isFetching,
465 isFetchingMore,
466 fetchMore,
467 canFetchMore,
468 } = useQuery(
469 'projects',
470 ({ offset } = {}) => fetch('/api/projects?offset=' + (offset || 0)),
471 {
472 paginated: true,
473 getCanFetchMore: (lastPage, allPages) => next.nextId,
474 }
475 )
476​
477 const loadMore = async () => {
478 try {
479 // Get the last page
480 const lastPage = data[data.length - 1]
481 // Get the last item's ID
482 const lastItemId = lastPage[lastPage.length - 1].id
483 // Fetch more with the offset ID + 1
484 await fetchMore({
485 offset: lastItemId + 1,
486 })
487 } catch {}
488 }
489​
490 return isLoading ? (
491 <p>Loading...</p>
492 ) : data ? (
493 <>
494 {data.map((page, i) => (
495 <React.Fragment key={i}>
496 {page.data.map(project => (
497 <p key={project.id}>{project.name}</p>
498 ))}
499 </React.Fragment>
500 ))}
501 <div>
502 {canFetchMore ? (
503 <button onClick={loadMore} disabled={isFetchingMore}>
504 {isFetchingMore ? 'Loading more...' : 'Load More'}
505 </button>
506 ) : (
507 'Nothing more to fetch.'
508 )}
509 </div>
510 <div>
511 {isFetching && !isFetchingMore ? 'Background Updating...' : null}
512 </div>
513 </>
514 ) : null
516```
517​
518#### What happens when a paginated query needs to be refetched?\*\*
519​
520When 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.
521​
522### Scroll Restoration
523​
524Out 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.
525​
526### Manual Querying
527​
528If you ever want to disable a query from automatically running, you can use the `manual = true` option. When `manual` is set to true:
529​
530- The query will not automatically refetch due to changes to their query function or variables.
531- The query will not automatically refetch due to `refetchQueries` options in other queries or via `useRefetchQuery` calls.
532​
533```js
534function Todos() {
535 const { data, isLoading, error, refetch, isFetching } = useQuery(
536 'todos',
537 fetchTodoList,
538 {
539 manual: true,
540 }
541 )
542​
543 return (
544 <>
545 <button onClick={() => refetch()}>Fetch Todos</button>
546​
547 {isLoading ? (
548 <span>Loading...</span>
549 ) : error ? (
550 <span>Error: {error.message}</span>
551 ) : data ? (
552 <>
553 <ul>
554 {data.map(todo => (
555 <li key={todo.id}>{todo.title}</li>
556 ))}
557 </ul>
558 </>
559 ) : null}
560 </>
561 )
563```
564​
565> Pro Tip: Don't use `manual` for dependent queries. Use [Dependent Queries](#dependent-queries) instead!
566​
567### Retries
568​
569When 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`).
570​
571You can configure retries both on a global level and an individual query level.
572​
573- Setting `retry = false` will disable retries
574- Setting `retry = 6` will retry failing requests 6 times before showing the final error thrown by the function
575- Setting `retry = true` will infinitely retry failing requests.
576​
577```js
578import { useQuery } from 'react-query'
579​
580// Make specific query retry a certain number of times
581const { data, isLoading, error } = useQuery(
582 ['todos', { page: 1 }],
583 fetchTodoList,
584 {
585 retry: 10, // Will retry failed requests 10 times before displaying an error
586 }
588```
589​
590### Retry Delay
591​
592By 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.
593​
594The default `retryDelay` is set to double (starting at `1000`ms) with each attempt, but not exceed 30 seconds:
595​
596```js
597// Configure for all queries
598import { ReactQueryConfigProvider } from 'react-query'
599​
600const queryConfig = {
601 retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000),
603​
604function App() {
605 return (
606 <ReactQueryConfigProvider config={queryConfig}>
607 ...
608 </ReactQueryConfigProvider>
609 )
611```
612​
613Though 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:
614​
615```js
616const { data, isLoading, error } = useQuery('todos', fetchTodoList, {
617 retryDelay: 10000, // Will always wait 1000ms to retry, regardless of how many retries
618})
619```
620​
621### Suspense Mode
622​
623React 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`.
624​
625Global configuration:
626​
627```js
628// Configure for all queries
629import { ReactQueryConfigProvider } from 'react-query'
630​
631const queryConfig = {
632 suspense: true,
634​
635function App() {
636 return (
637 <ReactQueryConfigProvider config={queryConfig}>
638 ...
639 </ReactQueryConfigProvider>
640 )
642```
643​
644Query configuration:
645​
646```js
647const { useQuery } from 'react-query'
648​
649// Enable for an individual query
650useQuery(queryKey, queryFn, { suspense: true })
651```
652​
653When 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.
654​
655## Mutations
656​
657Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, React Query exports a `useMutation` hook.
658​
659### Basic Mutations
660​
661Assuming the server implements a ping mutation, that returns "pong" string, here's an example of the most basic mutation:
662​
663```js
664const PingPong = () => {
665 const [mutate, { data, isLoading, error }] = useMutation(pingMutation)
666​
667 const onPing = async () => {
668 try {
669 const data = await mutate()
670 console.log(data)
671 // { ping: 'pong' }
672 } catch {
673 // Uh oh, something went wrong
674 }
675 }
676 return <button onClick={onPing}>Ping</button>
678```
679​
680Mutations without variables are not that useful, so let's add some variables to closer match reality.
681​
682### Mutation Variables
683​
684To pass `variables` to your `mutate` function, call `mutate` with an object.
685​
686```js
687const CreateTodo = () => {
688 const [title, setTitle] = useState('')
689 const [mutate] = useMutation(createTodo)
690​
691 const onCreateTodo = async e => {
692 // Prevent the form from refreshing the page
693 e.preventDefault()
694​
695 try {
696 await mutate({ title })
697 // Todo was successfully created
698 } catch (error) {
699 // Uh oh, something went wrong
700 }
701 }
702​
703 return (
704 <form onSubmit={onCreateTodo}>
705 <input
706 type="text"
707 value={title}
708 onChange={e => setTitle(e.target.value)}
709 />
710 <br />
711 <button type="submit">Create Todo</button>
712 </form>
713 )
715```
716​
717Even with just variables, mutations aren't all that special, but when used with the `refetchQueries` and `updateQuery` options, they become a very powerful tool.
718​
719### Invalidate and Refetch Queries from Mutations
720​
721When 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.
722​
723For example, assume we have a mutation to post a new todo:
724​
725```js
726const [mutate] = useMutation(postTodo)
727```
728​
729When 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.
730​
731```js
732// When this mutation succeeds, any queries with the `todos` or `reminders` query key will be refetched
733mutate(newTodo, { refetchQueries: ['todos', 'reminders'], })
734​
735// The 3 queries below will be refetched when the mutation above succeeds
736const todoListQuery = useQuery('todos', fetchTodoList)
737const todoListQuery = useQuery(['todos', { page: 1 }, fetchTodoList)
738const remindersQuery = useQuery('reminders', fetchReminders)
739```
740​
741You can even refetch queries with specific variables by passing a query key tuple to `refetchQueries`:
742​
743```js
744mutate(newTodo, { refetchQueries: [['todos', { status: 'done' }]] })
745​
746// The query below will be refetched when the mutation above succeeds
747const todoListQuery = useQuery(['todos', { status: 'done' }], fetchTodoList)
748// However, the following query below will NOT be refetched
749const todoListQuery = useQuery('todos', fetchTodoList)
750```
751​
752If you want to **only** refetch `todos` queries that don't have variables, you can pass a tuple with `variables` set to `false`:
753​
754```js
755mutate(newTodo, { refetchQueries: [['todos', false]] })
756​
757// The query below will be refetched when the mutation above succeeds
758const todoListQuery = useQuery(['todos'], fetchTodoList)
759// However, the following query below will NOT be refetched
760const todoListQuery = useQuery(['todos', { status: 'done' }], fetchTodoList)
761```
762​
763If 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`:
764​
765```js
766const [mutate] = useMutation(addTodo, { refetchQueries: ['todos'] })
767​
768const run = async () => {
769 try {
770 await mutate(todo, { waitForRefetchQueries: true })
771 console.log('I will only log after all refetchQueries are done refetching!')
772 } catch {}
774```
775​
776It'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:
777​
778```js
779const [mutate] = useMutation(addTodo, { refetchQueries: ['todos'] })
780​
781const run = async () => {
782 try {
783 await mutate(todo, { refetchQueriesOnFailure: true })
784 // Even if the above mutation fails, any `todos` queries will still be refetched.
785 } catch {}
787```
788​
789### Query Updates from Mutations
790​
791When 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:
792​
793```js
794const [mutate] = useMutation(editTodo)
795​
796mutate(
797 {
798 id: 5,
799 name: 'Do the laundry',
800 },
801 {
802 updateQuery: ['todo', { id: 5 }],
803 }
805​
806// The query below will be updated with the response from the mutation above when it succeeds
807const { data, isLoading, error } = useQuery(['todo', { id: 5 }], fetchTodoByID)
808```
809​
810## Manually or Optimistically Setting Query Data
811​
812In 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:
813​
814```js
815import { setQueryData } from 'react-query'
816​
817// Full replacement
818setQueryData(['todo', { id: 5 }], newTodo)
819​
820// or functional update
821setQueryData(['todo', { id: 5 }], previous => ({ ...previous, status: 'done' }))
822```
823​
824**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.
825​
826Should you choose that you do _not_ want to refetch the query automatically, you can set the `shouldRefetch` option to `false`:
827​
828```js
829import { setQueryData } from 'react-query'
830​
831// Mutate, but do not automatically refetch the query in the background
832setQueryData(['todo', { id: 5 }], newTodo, {
833 shouldRefetch: false,
834})
835```
836​
837## Displaying Background Fetching Loading States
838​
839A 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:
840​
841```js
842function Todos() {
843 const { data: todos, isLoading, isFetching } = useQuery('todos', fetchTodos)
844​
845 return isLoading ? (
846 <span>Loading...</span>
847 ) : todos ? (
848 <>
849 {isFetching ? <div>Refreshing...</div> : null}
850​
851 <div>
852 {todos.map(todo => (
853 <Todo todo={todo} />
854 ))}
855 </div>
856 </>
857 ) : null
859```
860​
861## Displaying Global Background Fetching Loading State
862​
863In 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:
864​
865```js
866import { useIsFetching } from 'react-query'
867​
868function GlobalLoadingIndicator() {
869 const isFetching = useIsFetching()
870​
871 return isFetching ? (
872 <div>Queries are fetching in the background...</div>
873 ) : null
875```
876​
877## Window-Focus Refetching
878​
879If a user leaves your application and returns to stale data, you may want to trigger an update in the background to update any stale queries. Thankfully, **React Query does this automatically for you**, but if you choose to disable it, you can use the `ReactQueryConfigProvider`'s `refetchAllOnWindowFocus` option to disable it:
880​
881```js
882const queryConfig = { refetchAllOnWindowFocus: false }
883​
884function App() {
885 return (
886 <ReactQueryConfigProvider config={queryConfig}>
887 ...
888 </ReactQueryConfigProvider>
889 )
891```
892​
893## Custom Query Key Serializers (Experimental)
894​
895> **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
896​
897If you absolutely despise the default query key and variable syntax, you can replace the default query key serializer with your own by using the `ReactQueryConfigProvider` hook's `queryKeySerializerFn` option:
898​
899```js
900const queryConfig = {
901 queryKeySerializerFn: userQueryKey => {
902 // Your custom logic here...
903​
904 return [fullQueryHash, queryGroupId, variablesHash, variables]
905 },
907​
908function App() {
909 return (
910 <ReactQueryConfigProvider config={queryConfig}>
911 ...
912 </ReactQueryConfigProvider>
913 )
915```
916​
917- `userQueryKey: any`
918 - This is the queryKey passed in `useQuery` and all other public methods and utilities exported by React Query.
919- `fullQueryHash: string`
920 - This must be a unique `string` representing the query and variables.
921 - It must be stable and deterministic and should not change if things like the order of variables is changed or shuffled.
922- `queryGroupId: string`
923 - This must be a unique `string` representing only the query type without any variables
924 - It must be stable and deterministic and should not change if the variables of the query change
925- `variablesHash: string`
926 - This must be a unique `string` representing only the variables of the query
927 - It must be stable and deterministic and should not change if things like the order of variables is changed or shuffled.
928- `variables: any`
929 - This is the object that will be passed to the `queryFn` when using `useQuery`.
930​
931> An additional `stableStringify` utility is also exported to help with stringifying objects to have sorted keys.
932​
933#### URL Query Key Serializer Example
934​
935The example below shows how to build your own serializer for use with urls and use it with React Query:
936​
937```js
938import { ReactQueryConfigProvider, stableStringify } from 'react-query'
939​
940function urlQueryKeySerializer(queryKey) {
941 // Deconstruct the url
942 let [url, params = ''] = queryKey.split('?')
943​
944 // Build the variables object
945 let variables = {}
946 params
947 .split('&')
948 .filter(Boolean)
949 .forEach(param => {
950 const [key, value] = param.split('=')
951 variables[key] = value
952 })
953​
954 // Use stableStringify to turn variables into a stable string
955 const variablesHash = Object.keys(variables).length
956 ? stableStringify(variables)
957 : ''
958​
959 // Remove trailing slashes from the url to make an ID
960 const queryGroupId = url.replace(/\/{1,}$/, '')
961​
962 const queryHash = `${id}_${variablesHash}`
963​
964 return [queryHash, queryGroupId, variablesHash, variables]
966​
967const queryConfig = {
968 queryKeySerializerFn: urlQueryKeySerializer,
970​
971function App() {
972 return (
973 <ReactQueryConfigProvider config={queryConfig}>
974 ...
975 </ReactQueryConfigProvider>
976 )
978​
979// Heck, you can even make your own custom useQueryHook!
980​
981function useUrlQuery(url, options) {
982 return useQuery(url, () => axios.get(url).then(res => res.data))
984​
985// Use it in your app!
986​
987function Todos() {
988 const todosQuery = useUrlQuery(`/todos`)
990​
991function FilteredTodos({ status = 'pending' }) {
992 const todosQuery = useFunctionQuery([getTodos, { status }])
994​
995function Todo({ id }) {
996 const todoQuery = useUrlQuery(`/todos/${id}`)
998​
999refetchQuery('/todos')
1000refetchQuery('/todos?status=pending')
1001refetchQuery('/todos/5')
1002```
1003​
1004#### Function Query Key Serializer Example
1005​
1006The example below shows how to you build your own functional serializer and use it with React Query:
1007​
1008```js
1009import { ReactQueryConfigProvider, stableStringify } from 'react-query'
1010​
1011// A map to keep track of our function pointers
1012const functionSerializerMap = new Map()
1013​
1014function functionQueryKeySerializer(queryKey) {
1015 if (!queryKey) {
1016 return []
1018​
1019 let queryFn = queryKey
1020 let variables
1021​
1022 if (Array.isArray(queryKey)) {
1023 queryFn = queryKey[0]
1024 variables = queryKey[1]
1026​
1027 // Get or create an ID for the function pointer
1028 const queryGroupId = functionSerializerMap.get(queryFn) || (() => {
1029 const id = Date.now()
1030 functionSerializerMap.set(queryFn, id)
1031 return id
1032 })()
1033​
1034 const variablesIsObject = isObject(variables)
1035​
1036 const variablesHash = variablesIsObject ? stableStringify(variables) : ''
1037​
1038 const queryHash = `${queryGroupId}_${variablesHash}`,
1039​
1040 return [
1041 queryHash,
1042 queryGroupId,
1043 variablesHash,
1044 variables,
1047​
1048const queryConfig = {
1049 queryKeySerializerFn: functionQueryKeySerializer,
1051​
1052function App() {
1053 return (
1054 <ReactQueryConfigProvider config={queryConfig}>
1055 ...
1056 </ReactQueryConfigProvider>
1059// Heck, you can even make your own custom useQueryHook!
1060​
1061function useFunctionQuery(functionTuple, options) {
1062 const [queryFn, variables] = Array.isArray(functionTuple) ? functionTuple : [functionTuple]
1063 return useQuery(functionTuple, queryFn, options)
1065​
1066// Use it in your app!
1067​
1068function Todos() {
1069 const todosQuery = useFunctionQuery(getTodos)
1071​
1072function FilteredTodos({ status = 'pending' }) {
1073 const todosQuery = useFunctionQuery([getTodos, { status }])
1075​
1076function Todo({ id }) {
1077 const todoQuery = useFunctionQuery([getTodo, { id }])
1079​
1080refetchQuery(getTodos)
1081refetchQuery([getTodos, { status: 'pending' }])
1082refetchQuery([getTodo, { id: 5}])
1083```
1084​
1085# API
1086​
1087## `useQuery`
1088​
1089```js
1090const {
1091 data,
1092 error,
1093 isFetching,
1094 isCached,
1095 failureCount,
1096 isLoading,
1097 refetch,
1098 // with pagination mode enabled
1099 isFetchingMore,
1100 canFetchMore,
1101 fetchMore,
1102} = useQuery(queryKey, queryFn, {
1103 manual,
1104 pagination,
1105 getCanFetchMore,
1106 staleTime,
1107 retry,
1108 retryDelay,
1109 suspense,
1111```
1112​
1113### Options
1114​
1115- `queryKey: String | [String, Variables: Object] | falsey | Function => queryKey`
1116 - **Required**
1117 - The query key to use for this query.
1118 - If a string is passed, it will be used as the query key
1119 - If a `[String, Object]` tuple is passed, they will be serialized into a stable query key. See [Query Keys](#query-keys) for more information.
1120 - If a falsey value is passed, the query will be disabled and not run automatically.
1121 - 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.
1122 - The query will automatically update when this key changes (if the key is not falsey and if `manual` is not set to `true`)
1123 - `Variables: Object`
1124 - If a tuple with variables is passed, this object should be **serializable**.
1125 - Nested arrays and objects are supported
1126 - The order of object keys is sorted to be stable before being serialized into the query key
1127- `queryFn: Function(variables) => Promise(data/error)`
1128 - **Required**
1129 - The function that the query will use to request data
1130 - 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 })`
1131 - Must return a promise that will either resolves data or throws an error.
1132- `pagination: Boolean`
1133 - Set this to `true` to enable pagination mode
1134 - In this mode, new pagination utilities are returned from `useQuery` and `data` becomes an array of page results
1135- `manual: Boolean`
1136 - Set this to `true` to disable automatic refetching when the query mounts or changes query keys.
1137 - To refetch the query, use the `refetch` method returned from the `useQuery` instance.
1138- `getCanFetchMore: Function(lastPage, allPages) => Boolean`
1139 - **Required if using `pagination` mode**
1140 - When using `pagination` mode, this function should return `true` if there is more data than can be fetched.
1141- `retry: Boolean | Int`
1142 - If `false`, failed queries will not retry by default
1143 - If `true`, failed queries will retry infinitely
1144 - If set to an `Int`, eg. `3`, failed queries will retry until the failed query count meets that number
1145- `retryDelay: Function(retryAttempt: Int) => Int`
1146 - This function receives a `retryAttempt` integer and returns the delay to apply before the next attempt in milliseconds
1147 - A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff
1148 - A function like `attempt => attempt * 1000` applies linear backoff.
1149- `staleTime: Int`
1150 - The time in milliseconds that cache data remains fresh. After a successful cache update, that cache data will become stale after this duration
1151- `cacheTime: Int`
1152 - 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.
1153- `refetchInterval: false | Integer`
1154 - Optional
1155 - If set to a number, all queries will continuously refetch at this frequency in milliseconds
1156- `suspense: Boolean`
1157 - Optional
1158 - Set this to `true` to enable suspense mode.
1159 - When `true`, `useQuery` will suspend when `isLoading` would normally be `true`
1160 - When `true`, `useQuery` will throw runtime errors when `error` would normally be truthy
1161​
1162### Returns
1163​
1164- `data: null | Any`
1165 - Defaults to `null`
1166 - The last successfully resolved data for the query.
1167- `error: null | Error`
1168 - The error object for the query, if an error was thrown.
1169- `isLoading: Boolean`
1170 - Will be `true` if the query is both fetching and does not have any cached data to display.
1171- `isFetching: Boolean`
1172 - Will be `true` if the query is currently fetching, including background fetching.
1173- `isCached: Boolean`
1174 - Will be `true` if the query's response is currently cached.
1175- `failureCount: Integer`
1176 - The failure count for the query.
1177 - Incremented every time the query fails.
1178 - Reset to `0` when the query succeeds.
1179- `refetch: Function({ variables: Object, merge: Function, disableThrow: Boolean })`
1180 - A function to manually refetch the query.
1181 - Supports custom variables (useful for "fetch more" calls)
1182 - Supports custom data merging (useful for "fetch more" calls)
1183 - Set `disableThrow` to true to disable this function from throwing if an error is encountered.
1184- `isFetchingMore: Boolean`
1185 - If using `pagination` mode, this will be `true` when fetching more results using the `fetchMore` function.
1186- `canFetchMore: Boolean`
1187 - If using `pagination` mode, this will be `true` if there is more data to be fetched (known via the required `getCanFetchMore` option function)
1188- `fetchMore: Function(variables) => Promise`
1189 - If using `pagination` mode, this function allows you to fetch the next "page" of results.
1190 - `variables` should be an object that is passed to your query function to retrieve the next page of results
1191​
1192## `useMutation`
1193​
1194```js
1195const [mutate, { data, isLoading, error }] = useMutation(mutationFn, {
1196 refetchQueries,
1197 refetchQueriesOnFailure,
1199​
1200const promise = mutate(variables, { updateQuery, waitForRefetchQueries })
1201```
1202​
1203### Options
1204​
1205- `mutationFn: Function(variables) => Promise`
1206 - **Required**
1207 - A function that performs an asynchronous task and returns a promise
1208- `refetchQueries: Array<QueryKey>`
1209 - Optional
1210 - When the mutation succeeds, these queries will be automatically refetched
1211 - Must be an array of query keys, eg. `['todos', ['todo', { id: 5 }], 'reminders']`
1212- `refetchQueriesOnFailure: Boolean`
1213 - Defaults to `false`
1214 - Set this to `true` if you want `refetchQueries` to be refetched regardless of the mutation succeeding.
1215- `variables: any`
1216 - Optional
1217 - The variables object to pass tot he `mutationFn`
1218- `updateQuery: QueryKey`
1219 - Optional
1220 - The query key for the individual query to update with the response from this mutation.
1221 - 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.
1222- `waitForRefetchQueries: Boolean`
1223 - Optional
1224 - If set to `true`, the promise returned by `mutate()` will not resolve until refetched queries are resolved as well.
1225​
1226### Returns
1227​
1228- `mutate: Function(variables, { updateQuery })`
1229 - The mutation function you can call with variables to trigger the mutation and optionally update a query with its response.
1230- `data: null | Any`
1231 - Defaults to `null`
1232 - The last successfully resolved data for the query.
1233- `error: null | Error`
1234 - The error object for the query, if an error was thrown.
1235- `isLoading: Boolean`
1236 - Will be `true` if the query is both fetching and does not have any cached data
1237- `promise: Promise`
1238 - The promise that is returned by the `mutationFn`
1239​
1240## `setQueryData`
1241​
1242`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.
1243​
1244```js
1245import { setQueryData } from 'react-query'
1246​
1247const maybePromise = setQueryData(queryKey, data, { shouldRefetch })
1248```
1249​
1250### Options
1251​
1252- `queryKey: QueryKey`
1253 - **Required**
1254 - The query key for the individual query to update with new data.
1255- `data: any | Function(old) => any`
1256 - **Required**
1257 - Must either be the new data or a function that receives the old data and returns the new data
1258- `shouldRefetch: Boolean`
1259 - Optional
1260 - Defaults to `true`
1261 - Set this to `false` to disable the automatic background refetch from happening
1262​
1263### Returns
1264​
1265- `maybePromise: undefined | Promise`
1266 - 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).
1267​
1268## `refetchQuery`
1269​
1270`refetchQuery` is a function for imperatively triggering a refetch of either:
1271​
1272- A group of queries
1273- A single query
1274​
1275By default, it will only refetch stale queries, but the `force` option can be used to refetch all queries, including non-stale ones.
1276​
1277```js
1278import { refetchQuery } from 'react-query'
1279​
1280const promise = refetchQuery(queryKey, { force })
1281```
1282​
1283### Options
1284​
1285- `queryKey: QueryKey`
1286 - **Required**
1287 - The query key for the query or query group to refetch.
1288 - 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' }]`).
1289 - 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)
1290 - 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' }]`)
1291- `force: Boolean`
1292 - Optional
1293 - Set this to true to force all queries to refetch instead of only stale ones.
1294​
1295### Returns
1296​
1297- `promise: Promise`
1298 - 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).
1299​
1300## `refetchAllQueries`
1301​
1302`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.
1303​
1304```js
1305import { refetchAllQueries } from 'react-query'
1306​
1307const promise = refetchAllQueries({ force, includeInactive })
1308```
1309​
1310### Options
1311​
1312- `force: Boolean`
1313 - Optional
1314 - Set this to `true` to force all queries to refetch instead of only stale ones.
1315- `includeInactive: Boolean`
1316 - Optional
1317 - Set this to `true` to also refetch inactive queries.
1318 - Overrides the `force` option to be `true`, regardless of it's value.
1319​
1320### Returns
1321​
1322- `promise: Promise`
1323 - 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).
1324​
1325## `useIsFetching`
1326​
1327`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)
1328​
1329```js
1330import { useIsFetching } from 'react-query'
1331​
1332const isFetching = useIsFetching()
1333```
1334​
1335### Returns
1336​
1337- `isFetching: Boolean`
1338 - Will be `true` if any query in your application is loading or fetching in the background
1339​
1340## `ReactQueryConfigProvider`
1341​
1342`ReactQueryConfigProvider` is an optional provider component and can be used to define defaults for all instances of `useQuery` within it's sub-tree:
1343​
1344```js
1345import { ReactQueryConfigProvider } from 'react-query'
1346​
1347const queryConfig = {
1348 retry: 3,
1349 retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000),
1350 staleTime: 0,
1351 cacheTime: 5 * 60 * 1000,
1352 refetchAllOnWindowFocus: true,
1353 refetchInterval: false,
1354 suspense: false,
1356​
1357function App() {
1358 return (
1359 <ReactQueryConfigProvider config={queryConfig}>
1360 ...
1361 </ReactQueryConfigProvider>
1364```
1365​
1366### Options
1367​
1368- `config: Object`
1369 - Must be **stable** or **memoized**. Do not create an inline object!
1370 - For a description of all config options, please see the [`useQuery` hook](#usequery).