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

README.md

495 lines16.2 KB

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