Open History to see the last commit
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>
71}
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,
86}
87β
88function App() {
89 return <ReactQueryProvider config={config}>...</ReactQueryProvider>
90}
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 )
122}
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 )
157}
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
245}
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 )
285}
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
315}
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,
332}
333β
334function App() {
335 return (
336 <ReactQueryProvider config={config}>
337 <Stuff />
338 </ReactQueryProvider>
339 )
340}
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),
359}
360β
361function App() {
362 return (
363 <ReactQueryProvider config={config}>
364 <Stuff />
365 </ReactQueryProvider>
366 )
367}
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>
399}
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 )
438}
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!')
527}
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 })
564}
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.