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 { isPending, submittedAt, variables, mutate, isError } = 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: async () => {
20 return await queryClient.invalidateQueries({ queryKey: ['todos'] })
21 },
22})
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 is `pending`:
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) => {
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β
128[//]: # 'Example'
129β
130### Updating a single todo
131β
132[//]: # 'Example2'
133β
134```tsx
135useMutation({
136 mutationFn: updateTodo,
137 // When mutate is called:
138 onMutate: async (newTodo) => {
139 // Cancel any outgoing refetches
140 // (so they don't overwrite our optimistic update)
141 await queryClient.cancelQueries({ queryKey: ['todos', newTodo.id] })
142β
143 // Snapshot the previous value
144 const previousTodo = queryClient.getQueryData(['todos', newTodo.id])
145β
146 // Optimistically update to the new value
147 queryClient.setQueryData(['todos', newTodo.id], newTodo)
148β
149 // Return a context with the previous and new todo
150 return { previousTodo, newTodo }
151 },
152 // If the mutation fails, use the context we returned above
153 onError: (err, newTodo, context) => {
154 queryClient.setQueryData(
155 ['todos', context.newTodo.id],
156 context.previousTodo,
157 )
158 },
159 // Always refetch after error or success:
160 onSettled: (newTodo) => {
161 queryClient.invalidateQueries({ queryKey: ['todos', newTodo.id] })
162 },
163})
164```
165β
166[//]: # 'Example2'
167β
168You can also use the `onSettled` function in place of the separate `onError` and `onSuccess` handlers if you wish:
169β
170[//]: # 'Example3'
171β
172```tsx
173useMutation({
174 mutationFn: updateTodo,
175 // ...
176 onSettled: (newTodo, error, variables, context) => {
177 if (error) {
178 // do something
179 }
180 },
181})
182```
183β
184[//]: # 'Example3'
185β
186## When to use what
187β
188If 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.
189β
190However, 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.