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

README.md

581 lines19.2 KB

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