Open History to see the last commit
1
2
3<img src='https://github.com/tannerlinsley/react-query/raw/master/media/logo.png' width='300'/>
4
5Hooks for fetching, caching and updating asynchronous data in React
6
7<!-- <a href="https://travis-ci.org/tannerlinsley/react-query" target="\_parent">
8 <img alt="" src="https://travis-ci.org/tannerlinsley/react-query.svg?branch=master" />
9</a> -->
10<a href="https://npmjs.com/package/react-query" target="\_parent">
11 <img alt="" src="https://img.shields.io/npm/dm/react-query.svg" />
12</a>
13<a href="https://bundlephobia.com/result?p=react-query@latest" target="\_parent">
14 <img alt="" src="https://badgen.net/bundlephobia/minzip/react-query@latest" />
15</a>
16<a href="https://spectrum.chat/react-query">
17 <img alt="Join the community on Spectrum" src="https://withspectrum.github.io/badge/badge.svg" />
18</a>
19<a href="https://github.com/tannerlinsley/react-query" target="\_parent">
20 <img alt="" src="https://img.shields.io/github/stars/tannerlinsley/react-query.svg?style=social&label=Star" />
21</a>
22<a href="https://twitter.com/tannerlinsley" target="\_parent">
23 <img alt="" src="https://img.shields.io/twitter/follow/tannerlinsley.svg?style=social&label=Follow" />
24</a>
25
26### [Become a Sponsor](https://github.com/sponsors/tannerlinsley)
27
28## Quick Features
29
30- Transport, protocol & backend agnostic data fetching
31- Auto Caching + Refetching (stale-while-revalidate, Window Refocus, Polling/Realtime)
32- Parallel + Dependent Queries
33- Mutations + Automatic Query Refetching
34- Multi-layer Cache + Garbage Collection
35- Load-More Pagination + Scroll Recovery
36- React Suspense Support
37- 4.2 kb (minzipped)
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
72A big thanks to both [Draqula](https://github.com/vadimdemedes/draqula) for inspiring a lot of React Query's original API and documentation and also [Zeit's SWR](https://github.com/zeit/swr) and it's creators for inspiring even further customizations and examples. You all rock!
73
74</details>
75
76## Examples
77
78- [Basic](./examples/basic)
79- [Custom Hooks](./examples/custom-hooks)
80- [Auto Refetching / Polling / Realtime](./examples/auto-refetching)
81- [Window Refocus Refetching](./examples/focus-refetching)
82- [Optimistic Updates](./examples/optimistic-updates)
83- [Load-More Pagination](./examples/load-more-pagination)
84- [Suspense CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-query/tree/master/examples/suspense)
85- [Playground CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-query/tree/master/examples/sandbox)
86
87# Documentation
88
89- [Installation](#installation)
90- [Queries](#queries)
91 - [Query Keys](#query-keys)
92 - [Query Variables](#query-variables)
93 - [Dependent Queries](#dependent-queries)
94 - [Caching & Invalidation](#caching--invalidation)
95 - [Pagination](#pagination)
96 - [Load-More/Infinite-Scroll Pagination](#load-more-pagination)
97 - [Scroll Restoration](#scroll-restoration)
98 - [Manual Querying](#manual-querying)
99 - [Retries](#retries)
100 - [Retry Delay](#retry-delay)
101 - [Suspense Mode](#suspense-mode)
102- [Mutations](#mutations)
103 - [Basic Mutations](#basic-mutations)
104 - [Mutation Variables](#mutation-variables)
105 - [Invalidate and Refetch Queries from Mutations](#invalidate-and-refetch-queries-from-mutations)
106 - [Query Updates from Mutations](#query-updates-from-mutations)
107- [Manually or Optimistically Setting Query Data](#manually-or-optimistically-setting-query-data)
108- [Displaying Background Fetching Loading States](#displaying-background-fetching-loading-states)
109- [Displaying Global Background Fetching Loading State](#displaying-global-background-fetching-loading-state)
110- [Window-Focus Refetching](#window-focus-refetching)
111- [API](#api)
112 - [`useQuery`](#usequery)
113 - [`useMutation`](#usemutation)
114 - [`setQueryData`](#setquerydata)
115 - [`refetchQuery`](#refetchquery)
116 - [`refetchAllQueries`](#refetchallqueries)
117 - [`useIsFetching`](#useisfetching)
118 - [`useReactQueryConfig`](#usereactqueryconfig)
119
120## Installation
121
122```bash
123$ npm i --save react-query
124# or
125$ yarn add react-query
126```
127
128## Queries
129
130To make a new query, call the `useQuery` hook with:
131
132- A **unique key for the query**
133- An **asynchronous function (or similar then-able)** to resolve the data
134
135```js
136const info = useQuery('todos', fetchTodoList)
137```
138
139The **unique key** you provide is used internally for refetching, caching, deduping related queries.
140
141This key can be whatever you'd like it to be as long as:
142
143- It changes when your query should be requested again
144- It is consistent across all instances of that specific query in your application
145
146The query `info` returned contains all information about the query and can be easily destructured and used in your component:
147
148```js
149function Todos() {
150 const { data, isLoading, error } = useQuery('todos', fetchTodoList)
151
152 return (
153 <div>
154 {isLoading ? (
155 <span>Loading...</span>
156 ) : error ? (
157 <span>Error: {error.message}</span>
158 ) : data ? (
159 <ul>
160 {data.map(todo => (
161 <li key={todo.id}>{todo.title}</li>
162 ))}
163 </ul>
164 ) : null}
165 </div>
166 )
167}
168```
169
170### Query Keys
171
172Since 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.
173
174> Pro Tip: Variables passed in the key are automatically passed to your query function!
175
176All of the following queries would result in using the same key:
177
178```js
179useQuery(['todos', { status, page }])
180useQuery(['todos', { page, status }])
181useQuery(['todos', { page, status, other: undefined }])
182```
183
184> Note: To aid you in your quest, if a query key is used that contains a `?` (like `todos?page=${page}&status=${status}`), you will see a gentle console warning to use the above format instead.
185
186### Query Variables
187
188To 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.
189
190```js
191function Todos({ status }) {
192 const { data, isLoading, error } = useQuery(
193 ['todos', { status, page }],
194 fetchTodoList // This is the same as `fetchTodoList({ status, page })`
195 )
196}
197```
198
199Whenever a query's key changes, the query will automatically update:
200
201```js
202function Todos() {
203 const [page, setPage] = useState(0)
204
205 const { data, isLoading, error } = useQuery(
206 ['todos', { page }],
207 fetchTodoList
208 )
209
210 const onNextPage = () => {
211 setPage(page => page + 1)
212 }
213
214 return (
215 <>
216 {/* ... */}
217 <button onClick={onNextPage}>Load next page</button>
218 </>
219 )
220}
221```
222
223### Dependent Queries
224
225React Query makes it easy to make queries that depends on other queries for both:
226
227- Parallel Queries (avoiding waterfalls) and
228- Serial Queries (when a piece of data is required for the next query to happen.
229
230To do this effectively, you can use the following 2 approaches:
231
232#### Pass a falsey query key
233
234If a query isn't ready to be requested yet, just pass a falsey value as the query key:
235
236```js
237const { data: user } = useQuery(['user', { userId }])
238const { data: projects } = useQuery(user && ['projects', { userId: user.id }]) // User is `null`, so the query key will be falsey
239```
240
241#### Use a query key function
242
243If a function is passed, the query will not execute until the function can be called without throwing:
244
245```js
246const { data: user } = useQuery(['user', { userId }])
247const { data: projects } = useQuery(() => ['projects', { userId: user.id }]) // This will throw until `user` is available
248```
249
250#### Mix them together!
251
252```js
253const [ready, setReady] = React.useState(false)
254const { data: user } = useQuery(ready && ['user', { userId }]) // Wait for ready
255const { data: projects } = useQuery(
256 () => ready && ['projects', { userId: user.id }] // Wait for ready and user.id
257```
258
259### Caching & Invalidation
260
261React Query caching is automatic out of the box. It uses a `stale-while-revalidate` in-memory caching model across queries along with query deduping to to always ensure a query's data is only stored once even if that query is used multiple times across your application.
262
263At a glance:
264
265- Caching is automatic and aggressive by default.
266- The cache is keyed on unique `query + variables` combinations.
267- 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)
268- Stale queries are automatically refetched whenever their **query keys change (this includes variables used in query key tuples)** or when **new usages/instances** of the query are mounted.
269- By default query results are **always** cached **when in use**.
270- If a query is no longer being used, it becomes inactive and by default is cached in the background for **5 minutes**. This time can be configured using the `cacheTime` option at both the global and query-level)
271- After a query is inactive for the time specified via the `cacheTime` option (defaults to 5 minutes), the query is deleted and garbage collected.
272
273<details>
274 <summary>A more detailed example of the caching lifecycle</summary>
275
276Let's assume we are using the default `cacheTime` of **5 minutes** and the default `staleTime` of `0`.
277
278- A new instance of `useQuery('todos', fetchTodos)` mounts
279 - 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.
280 - It will then cache the data using `'todos'` and `` as the unique identifiers for that cache.
281 - A stale invalidation is scheduled using the `staleTime` option as a delay (defaults to `0`, or immediately).
282- A second instance of `useQuery('todos', fetchTodos)` mounts elsewhere
283 - Because this exact data exist in the cache from the first instance of this query, that data is immediately returned from the cache
284 - Since the query is stale, it is refetched in the background automatically
285- Both instances of the `useQuery('todos', fetchTodos)` query are unmount and no longer in use.
286 - 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**).
287- No more instances of `useQuery('todos', fetchTodos)` appear within **5 minutes**
288 - This query and its data is deleted and garbage collected.
289
290</details>
291
292> **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.
293
294### Pagination
295
296If all you need is page-based pagination, where the previous set of data is replaced with a new one, this section is not applicable to your use-case. For that, you can increment the page variable and pass it to your query via variables.
297
298However, if your app needs to add more data to the list along with existing one (for example, infinite loading), React Query provides you with a way to fetch additional data without deleting the current data. Let's use page-based pagination for simplicity, but assume that we want to append new todo items at the end of the list.
299
300```js
301function Todos() {
302 const { data, isLoading, error, refetch, isFetching } = useQuery(
303 ['todos', { page: 1 }],
304 fetchTodoList
305 )
306
307 const onFetchMore = () => {
308 refetch({
309 variables: { page: data.pagination.nextPage },
310 merge: (prev, next) => ({
311 ...next,
312 // Merge the new todos with the existing ones
313 todos: [...prev.todos, ...next.todos],
314 }),
315 })
316 }
317
318 return isLoading ? (
319 <span>Loading...</span>
320 ) : error ? (
321 <span>Error: {error.message}</span>
322 ) : data ? (
323 <>
324 <ul>
325 {data.todos.map(todo => (
326 <li key={todo.id}>{todo.title}</li>
327 ))}
328 </ul>
329 {data.pagination.hasMore && (
330 <button disabled={isFetching} onClick={onFetchMore}>
331 {isFetching ? 'Loading more todos...' : 'Load more todos'}
332 </button>
333 )}
334 </>
335 ) : null
336}
337```
338
339### Load-More/Infinite-Scroll Pagination
340
341Rendering 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:
342
343```js
344fetch('/api/projects?cursor=0'
345// { data: [...], nextId: 3}
346fetch('/api/projects?cursor=3'
347// { data: [...], nextId: 6}
348fetch('/api/projects?cursor=6'
349// { data: [...], nextId: 9}
350```
351
352Using the `nextId` value in each page's response, we can configure `useQuery` to fetch more pages as needed:
353
354- Configure your query function to use optional pagination variables. We'll send through the `nextId` as the `cursor` for the next page request
355- Set the `paginated` option to `true`
356- Define a `getCanFetchMore` option to know if there is more data to load (it receives the `lastPage` and `allPages` as parameters)
357
358```js
359import { useQuery } from 'react-query'
360
361function Todos() {
362 const {
363 data: pages,
364 isLoading,
365 isFetching,
366 isFetchingMore,
367 fetchMore,
368 canFetchMore,
369 } = useQuery(
370 'todos',
371 ({ nextId } = {}) => fetch('/api/projects?cursor=' + (nextId || 0)),
372 {
373 paginated: true,
374 getCanFetchMore: (lastPage, allPages) => next.nextId,
375 }
376 )
377
378 // ...
379}
380```
381
382You'll notice a few new things now:
383
384- `data` is now an array of pages that contain query results, instead of the query results themselves
385- A `fetchMore` function is now available
386- A `canFetchMore` boolean is now available
387- An `isFetchingMore` boolean is now available
388
389These can now be used to render a "load more" list (this example uses an `offset` key):
390
391```js
392import { useQuery } from 'react-query'
393
394function Todos() {
395 const {
396 data: pages,
397 isLoading,
398 isFetching,
399 isFetchingMore,
400 fetchMore,
401 canFetchMore,
402 } = useQuery(
403 'projects',
404 ({ offset } = {}) => fetch('/api/projects?offset=' + (offset || 0)),
405 {
406 paginated: true,
407 getCanFetchMore: (lastPage, allPages) => next.nextId,
408 }
409 )
410
411 const loadMore = async () => {
412 try {
413 // Get the last page
414 const lastPage = data[data.length - 1]
415 // Get the last item's ID
416 const lastItemId = lastPage[lastPage.length - 1].id
417 // Fetch more with the offset ID + 1
418 await fetchMore({
419 offset: lastItemId + 1,
420 })
421 } catch {}
422 }
423
424 return isLoading ? (
425 <p>Loading...</p>
426 ) : data ? (
427 <>
428 {data.map((page, i) => (
429 <React.Fragment key={i}>
430 {page.data.map(project => (
431 <p key={project.id}>{project.name}</p>
432 ))}
433 </React.Fragment>
434 ))}
435 <div>
436 {canFetchMore ? (
437 <button onClick={loadMore} disabled={isFetchingMore}>
438 {isFetchingMore ? 'Loading more...' : 'Load More'}
439 </button>
440 ) : (
441 'Nothing more to fetch.'
442 )}
443 </div>
444 <div>
445 {isFetching && !isFetchingMore ? 'Background Updating...' : null}
446 </div>
447 </>
448 ) : null
449}
450```
451
452#### What happens when a paginated query needs to be refetched?\*\*
453
454When 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.
455
456### Scroll Restoration
457
458Out 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.
459
460### Manual Querying
461
462If you ever want to disable a query from automatically running, you can use the `manual = true` option. When `manual` is set to true:
463
464- The query will not automatically refetch due to changes to their query function or variables.
465- The query will not automatically refetch due to `refetchQueries` options in other queries or via `useRefetchQuery` calls.
466
467```js
468function Todos() {
469 const { data, isLoading, error, refetch, isFetching } = useQuery(
470 'todos',
471 fetchTodoList,
472 {
473 manual: true,
474 }
475 )
476
477 return (
478 <>
479 <button onClick={() => refetch()}>Fetch Todos</button>
480
481 {isLoading ? (
482 <span>Loading...</span>
483 ) : error ? (
484 <span>Error: {error.message}</span>
485 ) : data ? (
486 <>
487 <ul>
488 {data.map(todo => (
489 <li key={todo.id}>{todo.title}</li>
490 ))}
491 </ul>
492 </>
493 ) : null}
494 </>
495 )
496}
497```
498
499> Pro Tip: Don't use `manual` for dependent queries. Use [Dependent Queries](#dependent-queries) instead!
500
501### Retries
502
503When 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`).
504
505You can configure retries both on a global level and an individual query level.
506
507- Setting `retry = false` will disable retries
508- Setting `retry = 6` will retry failing requests 6 times before showing the final error thrown by the function
509- Setting `retry = true` will infinitely retry failing requests.
510
511```js
512import { useReactQueryConfig } from 'react-query'
513
514// Turn off retries for all queries
515useReactQueryConfig({
516 retry: false,
517})
518
519// Make specific query retry a certain number of times
520const { data, isLoading, error } = useQuery(
521 ['todos', { page: 1 }],
522 fetchTodoList,
523 {
524 retry: 10, // Will retry failed requests 10 times before displaying an error
525 }
526)
527```
528
529### Retry Delay
530
531By 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.
532
533The default `retryDelay` is set to double (starting at `1000`ms) with each attempt, but not exceed 30 seconds:
534
535```js
536// Configure for all queries
537import { useReactQueryConfig } from 'react-query'
538
539const config = {
540 retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000),
541}
542
543function App() {
544 useReactQueryConfig(config)
545
546 return <Stuff />
547}
548```
549
550Though 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:
551
552```js
553const { data, isLoading, error } = useQuery('todos', fetchTodoList, {
554 retryDelay: 10000, // Will always wait 1000ms to retry, regardless of how many retries
555})
556```
557
558### Suspense Mode
559
560React 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`:
561
562```js
563const { useReactQueryConfig, useQuery } from 'react-query'
564
565// Enable for all queries by default
566useReactQueryConfig({
567 suspense: true
568})
569
570// Enable for an individual query
571useQuery(queryKey, queryFn, { suspense: true })
572```
573
574When 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.
575
576## Mutations
577
578Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, React Query exports a `useMutation` hook.
579
580### Basic Mutations
581
582Assuming the server implements a ping mutation, that returns "pong" string, here's an example of the most basic mutation:
583
584```js
585const PingPong = () => {
586 const [mutate, { data, isLoading, error }] = useMutation(pingMutation)
587
588 const onPing = async () => {
589 try {
590 const data = await mutate()
591 console.log(data)
592 // { ping: 'pong' }
593 } catch {
594 // Uh oh, something went wrong
595 }
596 }
597 return <button onClick={onPing}>Ping</button>
598}
599```
600
601Mutations without variables are not that useful, so let's add some variables to closer match reality.
602
603### Mutation Variables
604
605To pass `variables` to your `mutate` function, call `mutate` with an object.
606
607```js
608const CreateTodo = () => {
609 const [title, setTitle] = useState('')
610 const [mutate] = useMutation(createTodo)
611
612 const onCreateTodo = async e => {
613 // Prevent the form from refreshing the page
614 e.preventDefault()
615
616 try {
617 await mutate({ title })
618 // Todo was successfully created
619 } catch (error) {
620 // Uh oh, something went wrong
621 }
622 }
623
624 return (
625 <form onSubmit={onCreateTodo}>
626 <input
627 type="text"
628 value={title}
629 onChange={e => setTitle(e.target.value)}
630 />
631 <br />
632 <button type="submit">Create Todo</button>
633 </form>
634 )
635}
636```
637
638Even with just variables, mutations aren't all that special, but when used with the `refetchQueries` and `updateQuery` options, they become a very powerful tool.
639
640### Invalidate and Refetch Queries from Mutations
641
642When 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.
643
644For example, assume we have a mutation to post a new todo:
645
646```js
647const [mutate] = useMutation(postTodo)
648```
649
650When 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.
651
652```js
653// When this mutation succeeds, any queries with the `todos` or `reminders` query key will be refetched
654mutate(newTodo, { refetchQueries: ['todos', 'reminders'], })
655
656// The 3 queries below will be refetched when the mutation above succeeds
657const todoListQuery = useQuery('todos', fetchTodoList)
658const todoListQuery = useQuery(['todos', { page: 1 }, fetchTodoList)
659const remindersQuery = useQuery('reminders', fetchReminders)
660```
661
662You can even refetch queries with specific variables by passing a query key tuple to `refetchQueries`:
663
664```js
665mutate(newTodo, { refetchQueries: [['todos', { status: 'done' }]] })
666
667// The query below will be refetched when the mutation above succeeds
668const todoListQuery = useQuery(['todos', { status: 'done' }], fetchTodoList)
669// However, the following query below will NOT be refetched
670const todoListQuery = useQuery('todos', fetchTodoList)
671```
672
673If you want to **only** refetch `todos` queries that don't have variables, you can pass a tuple with `variables` set to `false`:
674
675```js
676mutate(newTodo, { refetchQueries: [['todos', false]] })
677
678// The query below will be refetched when the mutation above succeeds
679const todoListQuery = useQuery(['todos'], fetchTodoList)
680// However, the following query below will NOT be refetched
681const todoListQuery = useQuery(['todos', { status: 'done' }], fetchTodoList)
682```
683
684If 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`:
685
686```js
687const [mutate] = useMutation(addTodo, { refetchQueries: ['todos'] })
688
689const run = async () => {
690 try {
691 await mutate(todo, { waitForRefetchQueries: true })
692 console.log('I will only log after all refetchQueries are done refetching!')
693 } catch {}
694}
695```
696
697It'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:
698
699```js
700const [mutate] = useMutation(addTodo, { refetchQueries: ['todos'] })
701
702const run = async () => {
703 try {
704 await mutate(todo, { refetchQueriesOnFailure: true })
705 // Even if the above mutation fails, any `todos` queries will still be refetched.
706 } catch {}
707}
708```
709
710### Query Updates from Mutations
711
712When 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:
713
714```js
715const [mutate] = useMutation(editTodo)
716
717mutate(
718 {
719 id: 5,
720 name: 'Do the laundry',
721 },
722 {
723 updateQuery: ['todo', { id: 5 }],
724 }
725)
726
727// The query below will be updated with the response from the mutation above when it succeeds
728const { data, isLoading, error } = useQuery(['todo', { id: 5 }], fetchTodoByID)
729```
730
731## Manually or Optimistically Setting Query Data
732
733In 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:
734
735```js
736import { setQueryData } from 'react-query'
737
738// Full replacement
739setQueryData(['todo', { id: 5 }], newTodo)
740
741// or functional update
742setQueryData(['todo', { id: 5 }], previous => ({ ...previous, status: 'done' }))
743```
744
745**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.
746
747Should you choose that you do _not_ want to refetch the query automatically, you can set the `shouldRefetch` option to `false`:
748
749```js
750import { setQueryData } from 'react-query'
751
752// Mutate, but do not automatically refetch the query in the background
753setQueryData(['todo', { id: 5 }], newTodo, {
754 shouldRefetch: false,
755})
756```
757
758## Displaying Background Fetching Loading States
759
760A 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:
761
762```js
763function Todos() {
764 const { data: todos, isLoading, isFetching } = useQuery('todos', fetchTodos)
765
766 return isLoading ? (
767 <span>Loading...</span>
768 ) : todos ? (
769 <>
770 {isFetching ? <div>Refreshing...</div> : null}
771
772 <div>
773 {todos.map(todo => (
774 <Todo todo={todo} />
775 ))}
776 </div>
777 </>
778 ) : null
779}
780```
781
782## Displaying Global Background Fetching Loading State
783
784In 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:
785
786```js
787import { useIsFetching } from 'react-query'
788
789function GlobalLoadingIndicator() {
790 const isFetching = useIsFetching()
791
792 return isFetching ? (
793 <div>Queries are fetching in the background...</div>
794 ) : null
795}
796```
797
798## Window-Focus Refetching
799
800If 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:
801
802```js
803useReactQueryConfig({ refetchAllOnWindowFocus: false })
804```
805
806# API
807
808## `useQuery`
809
810```js
811const {
812 data,
813 error,
814 isFetching,
815 isCached,
816 failureCount,
817 isLoading,
818 refetch,
819 // with pagination mode enabled
820 isFetchingMore,
821 canFetchMore,
822 fetchMore,
823} = useQuery(queryKey, queryFn, {
824 manual,
825 pagination,
826 getCanFetchMore,
827 staleTime,
828 retry,
829 retryDelay,
830 suspense,
831})
832```
833
834### Options
835
836- `queryKey: String | [String, Variables: Object] | falsey | Function => queryKey`
837 - **Required**
838 - The query key to use for this query.
839 - If a string is passed, it will be used as the query key
840 - If a `[String, Object]` tuple is passed, they will be serialized into a stable query key. See [Query Keys](#query-keys) for more information.
841 - If a falsey value is passed, the query will be disabled and not run automatically.
842 - 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.
843 - The query will automatically update when this key changes (if the key is not falsey and if `manual` is not set to `true`)
844 - `Variables: Object`
845 - If a tuple with variables is passed, this object should be **serializable**.
846 - Nested arrays and objects are supported
847 - The order of object keys is sorted to be stable before being serialized into the query key
848- `queryFn: Function(variables) => Promise(data/error)`
849 - **Required**
850 - The function that the query will use to request data
851 - 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 })`
852 - Must return a promise that will either resolves data or throws an error.
853- `pagination: Boolean`
854 - Set this to `true` to enable pagination mode
855 - In this mode, new pagination utilities are returned from `useQuery` and `data` becomes an array of page results
856- `manual: Boolean`
857 - Set this to `true` to disable automatic refetching when the query mounts or changes query keys.
858 - To refetch the query, use the `refetch` method returned from the `useQuery` instance.
859- `getCanFetchMore: Function(lastPage, allPages) => Boolean`
860 - **Required if using `pagination` mode**
861 - When using `pagination` mode, this function should return `true` if there is more data than can be fetched.
862- `retry: Boolean | Int`
863 - If `false`, failed queries will not retry by default
864 - If `true`, failed queries will retry infinitely
865 - If set to an `Int`, eg. `3`, failed queries will retry until the failed query count meets that number
866- `retryDelay: Function(retryAttempt: Int) => Int`
867 - This function receives a `retryAttempt` integer and returns the delay to apply before the next attempt in milliseconds
868 - A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff
869 - A function like `attempt => attempt * 1000` applies linear backoff.
870- `staleTime: Int`
871 - The time in milliseconds that cache data remains fresh. After a successful cache update, that cache data will become stale after this duration
872- `cacheTime: Int`
873 - 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.
874- `refetchInterval: false | Integer`
875 - Optional
876 - If set to a number, all queries will continuously refetch at this frequency in milliseconds
877- `suspense: Boolean`
878 - Optional
879 - Set this to `true` to enable suspense mode.
880 - When `true`, `useQuery` will suspend when `isLoading` would normally be `true`
881 - When `true`, `useQuery` will throw runtime errors when `error` would normally be truthy
882
883### Returns
884
885- `data: null | Any`
886 - Defaults to `null`
887 - The last successfully resolved data for the query.
888- `error: null | Error`
889 - The error object for the query, if an error was thrown.
890- `isLoading: Boolean`
891 - Will be `true` if the query is both fetching and does not have any cached data to display.
892- `isFetching: Boolean`
893 - Will be `true` if the query is currently fetching, including background fetching.
894- `isCached: Boolean`
895 - Will be `true` if the query's response is currently cached.
896- `failureCount: Integer`
897 - The failure count for the query.
898 - Incremented every time the query fails.
899 - Reset to `0` when the query succeeds.
900- `refetch: Function({ variables: Object, merge: Function, disableThrow: Boolean })`
901 - A function to manually refetch the query.
902 - Supports custom variables (useful for "fetch more" calls)
903 - Supports custom data merging (useful for "fetch more" calls)
904 - Set `disableThrow` to true to disable this function from throwing if an error is encountered.
905- `isFetchingMore: Boolean`
906 - If using `pagination` mode, this will be `true` when fetching more results using the `fetchMore` function.
907- `canFetchMore: Boolean`
908 - If using `pagination` mode, this will be `true` if there is more data to be fetched (known via the required `getCanFetchMore` option function)
909- `fetchMore: Function(variables) => Promise`
910 - If using `pagination` mode, this function allows you to fetch the next "page" of results.
911 - `variables` should be an object that is passed to your query function to retrieve the next page of results
912
913## `useMutation`
914
915```js
916const [mutate, { data, isLoading, error }] = useMutation(mutationFn, {
917 refetchQueries,
918 refetchQueriesOnFailure,
919})
920
921const promise = mutate(variables, { updateQuery, waitForRefetchQueries })
922```
923
924### Options
925
926- `mutationFn: Function(variables) => Promise`
927 - **Required**
928 - A function that performs an asynchronous task and returns a promise
929- `refetchQueries: Array<QueryKey>`
930 - Optional
931 - When the mutation succeeds, these queries will be automatically refetched
932 - Must be an array of query keys, eg. `['todos', ['todo', { id: 5 }], 'reminders']`
933- `refetchQueriesOnFailure: Boolean`
934 - Defaults to `false`
935 - Set this to `true` if you want `refetchQueries` to be refetched regardless of the mutation succeeding.
936- `variables: any`
937 - Optional
938 - The variables object to pass tot he `mutationFn`
939- `updateQuery: QueryKey`
940 - Optional
941 - The query key for the individual query to update with the response from this mutation.
942 - 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.
943- `waitForRefetchQueries: Boolean`
944 - Optional
945 - If set to `true`, the promise returned by `mutate()` will not resolve until refetched queries are resolved as well.
946
947### Returns
948
949- `mutate: Function(variables, { updateQuery })`
950 - The mutation function you can call with variables to trigger the mutation and optionally update a query with its response.
951- `data: null | Any`
952 - Defaults to `null`
953 - The last successfully resolved data for the query.
954- `error: null | Error`
955 - The error object for the query, if an error was thrown.
956- `isLoading: Boolean`
957 - Will be `true` if the query is both fetching and does not have any cached data
958- `promise: Promise`
959 - The promise that is returned by the `mutationFn`
960
961## `setQueryData`
962
963`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.
964
965```js
966import { setQueryData } from 'react-query'
967
968const maybePromise = setQueryData(queryKey, data, { shouldRefetch })
969```
970
971### Options
972
973- `queryKey: QueryKey`
974 - **Required**
975 - The query key for the individual query to update with new data.
976- `data: any | Function(old) => any`
977 - **Required**
978 - Must either be the new data or a function that receives the old data and returns the new data
979- `shouldRefetch: Boolean`
980 - Optional
981 - Defaults to `true`
982 - Set this to `false` to disable the automatic background refetch from happening
983
984### Returns
985
986- `maybePromise: undefined | Promise`
987 - 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).
988
989## `refetchQuery`
990
991`refetchQuery` is a function for imperatively triggering a refetch of either:
992
993- A group of queries
994- A single query
995
996By default, it will only refetch stale queries, but the `force` option can be used to refetch all queries, including non-stale ones.
997
998```js
999import { refetchQuery } from 'react-query'
1000
1001const promise = refetchQuery(queryKey, { force })
1002```
1003
1004### Options
1005
1006- `queryKey: QueryKey`
1007 - **Required**
1008 - The query key for the query or query group to refetch.
1009 - 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' }]`).
1010 - 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)
1011 - 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' }]`)
1012- `force: Boolean`
1013 - Optional
1014 - Set this to true to force all queries to refetch instead of only stale ones.
1015
1016### Returns
1017
1018- `promise: Promise`
1019 - 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).
1020
1021## `refetchAllQueries`
1022
1023`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.
1024
1025```js
1026import { refetchAllQueries } from 'react-query'
1027
1028const promise = refetchAllQueries({ force, includeInactive })
1029```
1030
1031### Options
1032
1033- `force: Boolean`
1034 - Optional
1035 - Set this to `true` to force all queries to refetch instead of only stale ones.
1036- `includeInactive: Boolean`
1037 - Optional
1038 - Set this to `true` to also refetch inactive queries.
1039 - Overrides the `force` option to be `true`, regardless of it's value.
1040
1041### Returns
1042
1043- `promise: Promise`
1044 - 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).
1045
1046## `useIsFetching`
1047
1048`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)
1049
1050```js
1051import { useIsFetching } from 'react-query'
1052
1053const isFetching = useIsFetching()
1054```
1055
1056### Returns
1057
1058- `isFetching: Boolean`
1059 - Will be `true` if any query in your application is loading or fetching in the background
1060
1061## `useReactQueryConfig`
1062
1063`useReactQueryConfig` is optional and can be used to define defaults for all instances of `useQuery` through your app:
1064
1065```js
1066import { useReactQueryConfig } from 'react-query'
1067
1068useReactQueryConfig({
1069 retry: 3,
1070 retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000),
1071 staleTime: 0,
1072 cacheTime: 5 * 60 * 1000,
1073 refetchAllOnWindowFocus: true,
1074 refetchInterval: false,
1075 suspense: false,
1076})
1077```
1078
1079### Options
1080
1081For a description of all options, please see the [`useQuery` hook](#usequery).
1082
1083### Returns
1084
1085This hook does not return anything
1086
1087### Example
1088
1089```js
1090const config = {
1091 // These are the default config options for the useReactQueryConfig
1092 retry: 3,
1093 retryDelay: attempt =>
1094 Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000),
1095 staleTime: 10 * 1000, // 10 seconds
1096 invalidCacheTime: 10 * 1000, // 10 seconds
1097}
1098
1099function App() {
1100 useReactQueryConfig({
1101 retry: 4
1102 })
1103
1104 return </>
1105}
1106```