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 orchestrating, caching and managing 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=@tannerlinsley/react-query-temp" target="\_parent">
14 <img alt="" src="https://badgen.net/bundlephobia/minzip/@tannerlinsley/react-query-temp" />
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<br />
26<br />
27<a href="https://patreon.com/tannerlinsley">
28 <img width="180" alt="" src="https://raw.githubusercontent.com/tannerlinsley/files/master/images/patreon/become-a-patron.png" />
29</a>
30β
31## The problem
32β
33Tools for managing async data and client stores/caches are plentiful these days, but most of these tools:
34β
35- Don't dedupe network operations that could be made in a single request
36- Force normalized or object/id-based caching strategies on your data
37- Don't invalidate their cache often enough, don't know when to invalidate, or don't ship with good defaults
38- Don't perform optimistic updates, or require setup to know when to perform them
39- Because of this βοΈ, they require imperative interaction to invalidate or manage their caches
40β
41## The solution
42β
43React Query contains a set of hooks that attempt to address these issues. Out of the box, React Query:
44β
45- Dedupes similar requests at the application level
46- Caches response data across similar requests
47- Optimistically updates requests in the background
48- Automatically manages query caching, invalidation, and garbage collection
49- Supports retries and exponential/custom back-off delays
50- Provides a declarative API for invalidating and atomically updating cached responses.
51- Built with and for React hooks
52- 3.8kb minzipped
53β
54## Hat Tipping
55β
56A big thanks to [Draqula](https://github.com/vadimdemedes/draqula) for inspiring a lot of React Query's API and documentation. You rock!
57β
58## Demos
59β
60- [A contrived CodeSandbox example](https://codesandbox.io/s/github/tannerlinsley/react-query/tree/master/example)
61β
62# Documentation
63β
64## Installation
65β
66```bash
67$ yarn add @tannerlinsley/react-query-temp
68# or
69$ npm i @tannerlinsley/react-query-temp --save
70```
71β
72## ReactQueryProvider
73β
74The `ReactQueryProvider` is a provider component that is necessary to use React Query. Render it at the base of your application like so:
75β
76```js
77import { ReactQueryProvider } from '@tannerlinsley/react-query-temp'
78β
79function App() {
80 return <ReactQueryProvider>...</ReactQueryProvider>
81}
82```
83β
84### Optional Configuration
85β
86You may also pass a config object to `ReactQueryProvider` as well to customize the default behavior of hooks like `useQuery` and `useMutation` used within it:
87β
88```js
89const config = {
90 // These are the default config options for the ReactQueryProvider
91 retry: 3,
92 retryDelay: attempt =>
93 Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000),
94 cacheTime: 10 * 1000, // 10 seconds
95 invalidCacheTime: 10 * 1000, // 10 seconds
96}
97β
98function App() {
99 return <ReactQueryProvider config={config}>...</ReactQueryProvider>
100}
101```
102β
103## Queries
104β
105### Basic queries
106β
107To perform a simple query without any options, simply pass the `useQuery` hook an **asynchronous function (or similar then-able)**:
108β
109```js
110import { useQuery } from '@tannerlinsley/react-query-temp'
111β
112import fetchTodoList from './queries/fetchTodoList'
113β
114function Todos() {
115 const { data, isLoading, error } = useQuery(fetchTodoList)
116β
117 return (
118 <div>
119 {isLoading ? (
120 <span>Loading...</span>
121 ) : error ? (
122 <span>Error: {error.message}</span>
123 ) : data ? (
124 <ul>
125 {data.map(todo => (
126 <li key={todo.id}>{todo.title}</li>
127 ))}
128 </ul>
129 ) : null}
130 </div>
131 )
132}
133```
134β
135### Query Variables
136β
137Using variables is as easy as passing a variables object to the query configuration:
138β
139```js
140const { data, isLoading, error } = useQuery(fetchTodoList, {
141 variables: {
142 status: 'done',
143 },
144})
145```
146β
147Whenever variables are updated, `useQuery` will automatically refetch and update the query for you:
148β
149```js
150function Todos() {
151 const [page, setPage] = useState(0)
152β
153 const { data, isLoading, error } = useQuery(fetchTodoList, {
154 variables: { page },
155 })
156β
157 const onNextPage = () => {
158 setPage(page => page + 1)
159 }
160β
161 return (
162 <>
163 {/* ... */}
164 <button onClick={onNextPage}>Load next page</button>
165 </>
166 )
167}
168```
169β
170If the same query (with the same variables) is used anywhere else in your application, it will get optimistically updated with the response
171β
172> **Hint:** Query functions **must be declared outside of the component** so as to maintain a single instance across your entire application. React Query uses query function equality to detect similar queries and cache responses.
173β
174### Caching
175β
176React Query caching is automatic and invalidates data very aggressively. It uses optimistic updates and short-term caching across similar queries to always ensure your query's data is only stored once, quickly available and kept up to date with the server.
177β
178At a glance:
179β
180- Caching is automatic and aggressive by default.
181- The cache is keyed on unique `query + variables` combinations.
182- You can configure the `cacheTime` option that determines how long cache data is considered fresh before it is marked as stale
183- You can configure the `inactiveCacheTime` option that determines how long unused stale cache data is kept around before it is garbage collected
184- Stale queries are optimistically and automatically updated when new instances of that query mount or variables change
185- If stale or unused cache data that has not been garbage collected is available, it will be used as a cold-start cache for queries while they are updated.
186- Data is not normalized or stored outside of the context of its usage.
187- Caching can be turned off either globally or individually for each query
188β
189> **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.
190β
191Here is a more detailed example of the caching lifecycle:
192β
193- A new usage of `useQuery(fetchTodoList, { page: 1 })` mounts
194 - 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.
195 - It will then cache the data using `fetchTodoList` and `{ page: 1 }` as the unique identifiers for that cache.
196 - A cache expiration is scheduled for later using the `cacheTime` option as a delay (defaults to `10 * 1000` milliseconds or `10` seconds).
197- A second instance of `useQuery(fetchTodoList, { page: 1 })` mounts elsewhere
198 - Because this exact data exist in the cache from the first instance of this query, that data is immediately returned from the cache
199- `10` seconds pass since the data came in for the first instance of this query
200 - The data for these queries is marked as outdated
201- A third instance of `useQuery(fetchTodoList, { page: 1 })` mounts elsewhere
202 - Because this exact data exist in the cache from the first and second instances of this query, that data is immediately returned from the cache
203 - However, since the data has been marked as outdated, a background request is made to updated the stale data
204 - Both this instance and the other first and second instances of this query get optimistically updated with the new data from the background request
205 - A new cache expiration is scheduled for later using the `cacheTime` option as a delay.
206- All 3 instances of the `useQuery(fetchTodoList, { page: 1 })` query unmount.
207 - Since there are no more active instances to this query combination, a fallback timeout is set using `inactiveCacheTime` to garbage collect the cache (defaults to `10 * 1000` milliseconds or `10` seconds).
208 - If there is an active cache expiration scheduled already, it will be used instead.
209- No more instances of `useQuery(fetchTodoList, { page: 1 })` appear within the timeout
210 - The cache for the this query is deleted and garbage collected.
211β
212### Pagination
213β
214If 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 simply increment the page variable and pass it to your query via variables.
215β
216However, 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.
217β
218```js
219function Todos() {
220 const { data, isLoading, error, refetch, isFetching } = useQuery(
221 fetchTodoList,
222 {
223 page: 1,
224 }
225 )
226β
227 const onFetchMore = () => {
228 refetch({
229 variables: { page: data.pagination.nextPage },
230 merge: (prev, next) => ({
231 ...next,
232 // Merge the new todos with the existing ones
233 todos: [...prev.todos, ...next.todos],
234 }),
235 })
236 }
237β
238 return isLoading ? (
239 <span>Loading...</span>
240 ) : error ? (
241 <span>Error: {error.message}</span>
242 ) : data ? (
243 <>
244 <ul>
245 {data.todos.map(todo => (
246 <li key={todo.id}>{todo.title}</li>
247 ))}
248 </ul>
249 {data.pagination.hasMore && (
250 <button disabled={isFetching} onClick={onFetchMore}>
251 {isFetching ? 'Loading more todos...' : 'Load more todos'}
252 </button>
253 )}
254 </>
255 ) : null
256}
257```
258β
259To prevent you from managing the loading state of `refetch` manually (since `isLoading` will remain false when `refetch` is called), React Query exposes an `isFetching` variable. It's the same as `isLoading`, but only reflects the state of the actual fetch operation for the query.
260β
261### Manual Querying
262β
263If you ever want to disable a query from automatically running when the query or variables change, you can use the `manual = true` option. When `manual` is set to true:
264β
265- The query will not automatically refetch due to changes to their query function or variables.
266- The query will not included in any `refetchQueries` options or `useRefetchQueries` calls. To override this, use the `includeManual` option in either.
267β
268```js
269function Todos() {
270 const { data, isLoading, error, refetch, isFetching } = useQuery(
271 fetchTodoList,
272 {
273 manual: true,
274 }
275 )
276β
277 return (
278 <>
279 <button onClick={() => refetch()}>Fetch Todos</button>
280β
281 {isLoading ? (
282 <span>Loading...</span>
283 ) : error ? (
284 <span>Error: {error.message}</span>
285 ) : data ? (
286 <>
287 <ul>
288 {data.map(todo => (
289 <li key={todo.id}>{todo.title}</li>
290 ))}
291 </ul>
292 </>
293 ) : null}
294 </>
295 )
296}
297```
298β
299This can also be useful under circumstances where you don't want your query firing because of unmet required conditions like a missing variable
300β
301```js
302function TodosByUser({ userID }) {
303 const { data, isLoading, error, refetch, isFetching } = useQuery(
304 fetchTodoListByUserID,
305 {
306 manual: !userID, // Don't auto fetch if there is no userID
307 variables: {
308 userID,
309 },
310 }
311 )
312β
313 return isLoading ? (
314 <span>Loading...</span>
315 ) : error ? (
316 <span>Error: {error.message}</span>
317 ) : data ? (
318 <>
319 <ul>
320 {data.map(todo => (
321 <li key={todo.id}>{todo.title}</li>
322 ))}
323 </ul>
324 </>
325 ) : null
326}
327```
328β
329### Retries
330β
331When 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`).
332β
333You can configure retries both on a global level and an individual query level.
334β
335- Setting `retry = false` will disable retries
336- Setting `retry = 6` will retry failing requests 6 times before showing the final error thrown by the function
337- Setting `retry = true` will infinitely retry failing requests.
338β
339```js
340// Turn off retries for all queries
341const config = {
342 retry: false,
343}
344β
345function App() {
346 return (
347 <ReactQueryProvider config={config}>
348 <Stuff />
349 </ReactQueryProvider>
350 )
351}
352β
353// Make specific query retry a certain number of times
354const { data, isLoading, error } = useQuery(fetchTodoList, {
355 variables: { page: 1 },
356 retry: 10, // Will retry failed requests 10 times before displaying an error
357})
358```
359β
360### Retry Delay with `retryDelay`
361β
362By 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.
363β
364The default `retryDelay` is set to double (starting at `1000`ms) with each attempt, but not exceed 30 seconds:
365β
366```js
367// Configure for all queries
368const config = {
369 retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000),
370}
371β
372function App() {
373 return (
374 <ReactQueryProvider config={config}>
375 <Stuff />
376 </ReactQueryProvider>
377 )
378}
379```
380β
381Though 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:
382β
383```js
384const { data, isLoading, error } = useQuery(fetchTodoList, {
385 retryDelay: 10000, // Will always wait 1000ms to retry, regardless of how many retries
386})
387```
388β
389## Mutations
390β
391Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, React Query offers a `useMutation` hook. Just like queries, remember to define your mutations outside your components to prevent infinite unnecessary rerenders.
392β
393### Basic Mutations
394β
395Assuming the server implements a ping mutation, that simply returns "pong" string, here's an example of the most basic mutation:
396β
397```js
398// pingMutation is a function that returns a promise
399import pingMutation from '../queries/pingMutation'
400β
401const PingPong = () => {
402 const [mutate, { data, isLoading, error }] = useMutation(pingMutation)
403β
404 const onPing = async () => {
405 const data = await mutate()
406 console.log(data)
407 // { ping: 'pong' }
408 }
409 return <button onClick={onPing}>Ping</button>
410}
411```
412β
413Mutations without variables are not that useful, so let's add some variables to closer match reality.
414β
415### Mutation Variables
416β
417Similar to `useQuery`, `useMutation` also accepts variables. The only difference is that you pass `variables` to the `mutate` function, instead of the `useMutation` hook:
418β
419```js
420import createTodo from '../mutations/createTodo'
421β
422const CreateTodo = () => {
423 const [title, setTitle] = useState('')
424 const [mutate] = useMutation(createTodo)
425β
426 const onCreateTodo = async e => {
427 // Prevent the form from refreshing the page
428 e.preventDefault()
429β
430 try {
431 await mutate({ title })
432 // Todo was successfully created
433 } catch (error) {
434 // Uh oh, something went wrong
435 }
436 }
437β
438 return (
439 <form onSubmit={onCreateTodo}>
440 <input
441 type="text"
442 value={title}
443 onChange={e => setTitle(e.target.value)}
444 />
445 <br />
446 <button type="submit">Create Todo</button>
447 </form>
448 )
449}
450```
451β
452### Refetching Queries from Mutations
453β
454When a mutation succeeds, it's likely that other queries in your application need to update. For example, a successful `postTodo` mutation will likely require that any `fetchTodoList` queries get updated to show the new todo item.
455β
456Where 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 uses **atomic updates** instead of partial manipulation of caches.
457β
458To automatically refetch queries after a mutation succeeds, you can use the `useMutation` hook's `refetchQueries` option:
459β
460```js
461import fetchTodoList from '../queries/fetchTodoList'
462import createTodo from '../mutations/createTodo'
463β
464// When this mutation succeeds, any query relying on `fetchTodoList` query will be refetched
465const [mutate] = useMutation(createTodo, { refetchQueries: [fetchTodoList] })
466β
467// The 2 queries below will be refetched when the mutation above succeeds
468const { data, isLoading, error } = useQuery(fetchTodoList)
469const { data, isLoading, error } = useQuery(fetchTodoList, {
470 variables: { status: 'done' },
471})
472```
473β
474It's easy to refetch multiple queries too:
475β
476```js
477import fetchTodoList from '../queries/fetchTodoList'
478import fetchReminders from '../queries/fetchReminders'
479import createTodo from '../mutations/createTodo'
480β
481// When this mutation succeeds, any query relying on `fetchTodoList` query will be refetched
482const [mutate] = useMutation(createTodo, {
483 refetchQueries: [fetchTodoList, fetchReminders],
484})
485β
486// The 2 queries below will be refetched when the mutation above succeeds
487const todoListQuery = useQuery(fetchTodoList)
488const remindersQuery = useQuery(fetchReminders)
489```
490β
491You can even refetch queries with specific variables by passing objects to `refetchQueries`
492β
493```js
494import fetchTodoList from '../queries/fetchTodoList'
495import addTodo from '../mutations/addTodo'
496β
497// You can lazily pass invalidation options to the `mutate` function instead
498const [mutate] = useMutation(addTodo, {
499 refetchQueries: [
500 {
501 query: fetchTodoList,
502 variables: {
503 type: 'done',
504 },
505 },
506 ],
507})
508β
509// The query below will be refetched when the mutation above succeeds
510const { data, isLoading, error } = useQuery(fetchTodoList, {
511 variables: {
512 type: 'done',
513 },
514})
515β
516// The query below will NOT be refetched when the mutation succeeds
517const { data, isLoading, error } = useQuery(fetchTodoList)
518```
519β
520If you prefer that the promise returned from `mutate()` only resolves **after** any `refetchQueries` have been refetched, you can set `waitForRefetchQueries = true`:
521β
522```js
523const [mutate] = useMutation(addTodo, {
524 waitForRefetchQueries: true,
525 refetchQueries: [
526 {
527 query: fetchTodoList,
528 variables: {
529 type: 'done',
530 },
531 },
532 ],
533})
534β
535const run = async () => {
536 await mutate(todo)
537 console.log('I will only log after all refetchQueries are done refetching!')
538}
539```
540β
541You can also lazily define mutation options with the `mutate` function:
542β
543```js
544const [mutate] = useMutation(addTodo)
545β
546// Wait to call the function to define the refetchQueries
547mutate(todo, {
548 refetchQueries: [fetchTodoList],
549})
550```
551β
552### Query Updates from Mutations
553β
554Normally when dealing with REST calls that **update** objects on the server, the updated version of that object is returned in the response. Instead of invalidating queries that would return that same object and wasting a network call, we can update query responses that match that exact object query using the `updateQueries` option:
555β
556> **NOTE:** The `updatedQueries` option can only be passed to the `mutate` function. Passing it to `useMutation` will have no effect
557β
558```js
559import fetchTodoByID from '../queries/fetchTodoByID'
560import editTodo from '../mutations/editTodo'
561β
562const [mutate] = useMutation(editTodo)
563β
564const saveTodo = async todo => {
565 await mutate(todo, {
566 updateQueries: [
567 {
568 query: fetchTodoByID,
569 variables: {
570 id: todo.id,
571 },
572 },
573 ],
574 })
575}
576β
577saveTodo({
578 id: 5,
579 name: 'Do the laundry',
580})
581β
582// The query below will be updated with the response from the mutation above when it succeeds
583const { data, isLoading, error } = useQuery(fetchTodoByID, {
584 variables: {
585 id: 5,
586 },
587})
588```
589β
590# API
591β
592## `ReactQueryProvider`
593β
594`ReactQueryProvider` is required and can optionally define defaults for all instances of `useQuery` and `useMutation` through your app
595β
596### Options
597β
598Pass options to `ReactQueryProvider` by pass it a `config` prop:
599β
600```js
601<ReactQueryProvider config={{...}}>
602 ...
603</ReactQueryProvider>
604```
605β
606- `retry: Boolean | Int`
607 - If `false`, failed queries will not retry by default
608 - If `true`, failed queries will retry infinitely
609 - If set to an `Int`, eg. `3`, failed queries will retry until the failed query count meets that number
610- `retryDelay: Function(retryAttempt: Int) => Int`
611 - This function receives a `retryAttempt` integer and returns the delay to apply before the next attempt in milliseconds
612 - A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff
613 - A function like `attempt => attempt * 1000` applies linear backoff.
614- `cacheTime: Int`
615 - The time in milliseconds that cache data remains fresh. After a successful cache update, that cache data will become stale after this duration
616- `invalidCacheTime: Int`
617 - 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.
618β
619## `useQuery`
620β
621### Options
622β
623Pass options to `useQuery` like so:
624β
625```js
626useQuery(query, { variables, queryID, manual, retry })
627```
628β
629- `query: Function(variables) => Promise(data/error)`
630 - The function that this query will use to fetch data
631 - **Must be defined only across your entire app.** (or a `queryID` must be optionally used)
632 - Receives the `variables` object passed to `useQuery(query, { variables })` or `refetch({ variables })`
633 - Must return a promise that either resolves data or throws an error
634- `variables`
635 - ...to be continued