Open History to see the last commit
1---
2id: optimistic-updates
3title: Optimistic Updates
4---
5β
6React Query provides two ways to optimistically update your UI before a mutation has completed. You can either use the `onMutate` option to update your cache directly, or leverage the returned `variables` to update your UI from the `useMutation` result.
7β
8## Via the UI
9β
10This is the simpler variant, as it doesn't interact with the cache directly.
11β
12[//]: # 'ExampleUI1'
13```tsx
14 const { isPending, submittedAt, variables, mutate, isError } = useMutation({
15 mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
16 // make sure to _return_ the Promise from the query invalidation
17 // so that the mutation stays in `pending` state until the refetch is finished
18 onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
19 })
20```
21[//]: # 'ExampleUI1'
22β
23you will then have access to `addTodoMutation.variables`, which contain the added todo. In your UI list, where the query is rendered, you can append another item to the list while the mutation is `pending`:
24β
25[//]: # 'ExampleUI2'
26```tsx
27<ul>
28 {todoQuery.items.map((todo) => (
29 <li key={todo.id}>{todo.text}</li>
30 ))}
31 {isPending && (
32 <li
33 key={String(submittedAt)}
34 style={{ opacity: 0.5 }}
35 >
36 {variables}
37 </li>
38 )}
39</ul>
40```
41[//]: # 'ExampleUI2'
42β
43The `submittedAt` property is a timestamp that is set when `mutate` is invoked. This is useful to create a unique key for the pending todo item. We've also added an `opacity` to indicate that this item is only temporarily here. Once the mutation completes, the item will be removed because the mutation is no longer `pending`. Given that the refetch succeeded, we should see the item as a "normal item" in our list.
44β
45If the mutation errors, the item will also disappear. But we could continue to show it, if we want, by checking for the `isError` state of the mutation. `variables` are _not_ cleared when the mutation errors, so we can still access them, maybe even show a retry button:
46β
47[//]: # 'ExampleUI3'
48```tsx
49{isError && (
50 <li
51 key={String(submittedAt)}
52 style={{ color: 'red' }}
53 >
54 {variables}
55 <button onClick={() => mutate(variables)}>
56 Retry
57 </button>
58 </li>
59)}
60```
61[//]: # 'ExampleUI3'
62β
63### If the mutation and the query don't live in the same component
64β
65This approach works very will if the mutation and the query live in the same component, However, you also get access to all mutations in other components via the dedicated `useMutationState` hook. It is best combined with a `mutationKey`:
66β
67[//]: # 'ExampleUI4'
68```tsx
69// somewhere in your app
70const { mutate } = useMutation({
71 mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
72 onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
73 mutationKey: ['addTodo']
74})
75β
76// access variables somewhere else
77const variables = useMutationState<string>({
78 filters: { mutationKey: ['addTodo'], status: 'pending' },
79 select: (mutation) => mutation.state.variables
80})
81```
82[//]: # 'ExampleUI4'
83β
84`variables` will be an `Array`, because there might be multiple mutations running at the same time. This will even make displaying concurrent optimistic updates a breeze.
85β
86## Via the cache
87β
88When you optimistically update your state before performing a mutation, there is a chance that the mutation will fail. In most of these failure cases, you can just trigger a refetch for your optimistic queries to revert them to their true server state. In some circumstances though, refetching may not work correctly and the mutation error could represent some type of server issue that won't make it possible to refetch. In this event, you can instead choose to rollback your update.
89β
90To do this, `useMutation`'s `onMutate` handler option allows you to return a value that will later be passed to both `onError` and `onSettled` handlers as the last argument. In most cases, it is most useful to pass a rollback function.
91β
92### Updating a list of todos when adding a new todo
93β
94[//]: # 'Example'
95β
96```tsx
97const queryClient = useQueryClient()
98β
99useMutation({
100 mutationFn: updateTodo,
101 // When mutate is called:
102 onMutate: async (newTodo) => {
103 // Cancel any outgoing refetches
104 // (so they don't overwrite our optimistic update)
105 await queryClient.cancelQueries({ queryKey: ['todos'] })
106β
107 // Snapshot the previous value
108 const previousTodos = queryClient.getQueryData(['todos'])
109β
110 // Optimistically update to the new value
111 queryClient.setQueryData(['todos'], (old) => [...old, newTodo])
112β
113 // Return a context object with the snapshotted value
114 return { previousTodos }
115 },
116 // If the mutation fails,
117 // use the context returned from onMutate to roll back
118 onError: (err, newTodo, context) => {
119 queryClient.setQueryData(['todos'], context.previousTodos)
120 },
121 // Always refetch after error or success:
122 onSettled: () => {
123 queryClient.invalidateQueries({ queryKey: ['todos'] })
124 },
125})
126```
127[//]: # 'Example'
128β
129### Updating a single todo
130β
131[//]: # 'Example2'
132```tsx
133useMutation({
134 mutationFn: updateTodo,
135 // When mutate is called:
136 onMutate: async (newTodo) => {
137 // Cancel any outgoing refetches
138 // (so they don't overwrite our optimistic update)
139 await queryClient.cancelQueries({ queryKey: ['todos', newTodo.id] })
140β
141 // Snapshot the previous value
142 const previousTodo = queryClient.getQueryData(['todos', newTodo.id])
143β
144 // Optimistically update to the new value
145 queryClient.setQueryData(['todos', newTodo.id], newTodo)
146β
147 // Return a context with the previous and new todo
148 return { previousTodo, newTodo }
149 },
150 // If the mutation fails, use the context we returned above
151 onError: (err, newTodo, context) => {
152 queryClient.setQueryData(
153 ['todos', context.newTodo.id],
154 context.previousTodo,
155 )
156 },
157 // Always refetch after error or success:
158 onSettled: (newTodo) => {
159 queryClient.invalidateQueries({ queryKey: ['todos', newTodo.id] })
160 },
161})
162```
163[//]: # 'Example2'
164β
165You can also use the `onSettled` function in place of the separate `onError` and `onSuccess` handlers if you wish:
166β
167[//]: # 'Example3'
168```tsx
169useMutation({
170 mutationFn: updateTodo,
171 // ...
172 onSettled: (newTodo, error, variables, context) => {
173 if (error) {
174 // do something
175 }
176 },
177})
178```
179[//]: # 'Example3'
180β
181β
182## When to use what
183β
184If you only have one place where the optimistic result should be shown, using `variables` and updating the UI directly is the approach that requires less code and is generally easier to reason about. For example, you don't need to handle rollbacks at all.
185β
186However, if you have multiple places on the screen that would require to know about the update, manipulating the cache directly will take care of this for you automatically.