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β
14```tsx
15const addTodoMutation = useMutation({
16 mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
17 // make sure to _return_ the Promise from the query invalidation
18 // so that the mutation stays in `pending` state until the refetch is finished
19 onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
20})
21β
22const { isPending, submittedAt, variables, mutate, isError } = addTodoMutation
23```
24β
25[//]: # 'ExampleUI1'
26β
27you 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 `isPending`:
28β
29[//]: # 'ExampleUI2'
30β
31```tsx
32<ul>
33 {todoQuery.items.map((todo) => (
34 <li key={todo.id}>{todo.text}</li>
35 ))}
36 {isPending && <li style={{ opacity: 0.5 }}>{variables}</li>}
37</ul>
38```
39β
40[//]: # 'ExampleUI2'
41β
42We're rendering a temporary item with a different `opacity` as long as the mutation is pending. Once it completes, the item will automatically no longer be rendered. Given that the refetch succeeded, we should see the item as a "normal item" in our list.
43β
44If 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:
45β
46[//]: # 'ExampleUI3'
47β
48```tsx
49{
50 isError && (
51 <li style={{ color: 'red' }}>
52 {variables}
53 <button onClick={() => mutate(variables)}>Retry</button>
54 </li>
55 )
56}
57```
58β
59[//]: # 'ExampleUI3'
60β
61### If the mutation and the query don't live in the same component
62β
63This approach works very well 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`:
64β
65[//]: # 'ExampleUI4'
66β
67```tsx
68// somewhere in your app
69const { mutate } = useMutation({
70 mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
71 onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
72 mutationKey: ['addTodo'],
73})
74β
75// access variables somewhere else
76const variables = useMutationState<string>({
77 filters: { mutationKey: ['addTodo'], status: 'pending' },
78 select: (mutation) => mutation.state.variables,
79})
80```
81β
82[//]: # 'ExampleUI4'
83β
84`variables` will be an `Array`, because there might be multiple mutations running at the same time. If we need a unique key for the items, we can also select `mutation.state.submittedAt`. 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 roll back 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, context) => {
103 // Cancel any outgoing refetches
104 // (so they don't overwrite our optimistic update)
105 await context.client.cancelQueries({ queryKey: ['todos'] })
106β
107 // Snapshot the previous value
108 const previousTodos = context.client.getQueryData(['todos'])
109β
110 // Optimistically update to the new value
111 context.client.setQueryData(['todos'], (old) => [...old, newTodo])
112β
113 // Return a result with the snapshotted value
114 return { previousTodos }
115 },
116 // If the mutation fails,
117 // use the result returned from onMutate to roll back
118 onError: (err, newTodo, onMutateResult, context) => {
119 context.client.setQueryData(['todos'], onMutateResult.previousTodos)
120 },
121 // Always refetch after error or success:
122 onSettled: (data, error, variables, onMutateResult, context) =>
123 context.client.invalidateQueries({ queryKey: ['todos'] }),
124})
125```
126β
127[//]: # 'Example'
128β
129### Updating a single todo
130β
131[//]: # 'Example2'
132β
133```tsx
134useMutation({
135 mutationFn: updateTodo,
136 // When mutate is called:
137 onMutate: async (newTodo, context) => {
138 // Cancel any outgoing refetches
139 // (so they don't overwrite our optimistic update)
140 await context.client.cancelQueries({ queryKey: ['todos', newTodo.id] })
141β
142 // Snapshot the previous value
143 const previousTodo = context.client.getQueryData(['todos', newTodo.id])
144β
145 // Optimistically update to the new value
146 context.client.setQueryData(['todos', newTodo.id], newTodo)
147β
148 // Return a result with the previous and new todo
149 return { previousTodo, newTodo }
150 },
151 // If the mutation fails, use the result we returned above
152 onError: (err, newTodo, onMutateResult, context) => {
153 context.client.setQueryData(
154 ['todos', onMutateResult.newTodo.id],
155 onMutateResult.previousTodo,
156 )
157 },
158 // Always refetch after error or success:
159 onSettled: (newTodo, error, variables, onMutateResult, context) =>
160 context.client.invalidateQueries({ queryKey: ['todos', newTodo.id] }),
161})
162```
163β
164[//]: # 'Example2'
165β
166You can also use the `onSettled` function in place of the separate `onError` and `onSuccess` handlers if you wish:
167β
168[//]: # 'Example3'
169β
170```tsx
171useMutation({
172 mutationFn: updateTodo,
173 // ...
174 onSettled: async (newTodo, error, variables, onMutateResult, context) => {
175 if (error) {
176 // do something
177 }
178 },
179})
180```
181β
182[//]: # 'Example3'
183β
184## When to use what
185β
186If 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.
187β
188However, 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.
189β
190[//]: # 'Materials'
191β
192## Further reading
193β
194Have a look at the guide by TkDodo on [Concurrent Optimistic Updates](https://tkdodo.eu/blog/concurrent-optimistic-updates-in-react-query).
195β
196[//]: # 'Materials'