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: async () => {
20 return await queryClient.invalidateQueries({ queryKey: ['todos'] })
21 },
22})
23β
24const { isPending, submittedAt, variables, mutate, isError } = addTodoMutation
25```
26β
27[//]: # 'ExampleUI1'
28β
29you 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`:
30β
31[//]: # 'ExampleUI2'
32β
33```tsx
34<ul>
35 {todoQuery.items.map((todo) => (
36 <li key={todo.id}>{todo.text}</li>
37 ))}
38 {isPending && <li style={{ opacity: 0.5 }}>{variables}</li>}
39</ul>
40```
41β
42[//]: # 'ExampleUI2'
43β
44We'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.
45β
46If 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:
47β
48[//]: # 'ExampleUI3'
49β
50```tsx
51{
52 isError && (
53 <li style={{ color: 'red' }}>
54 {variables}
55 <button onClick={() => mutate(variables)}>Retry</button>
56 </li>
57 )
58}
59```
60β
61[//]: # 'ExampleUI3'
62β
63### If the mutation and the query don't live in the same component
64β
65This 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`:
66β
67[//]: # 'ExampleUI4'
68β
69```tsx
70// somewhere in your app
71const { mutate } = useMutation({
72 mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
73 onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
74 mutationKey: ['addTodo'],
75})
76β
77// access variables somewhere else
78const variables = useMutationState<string>({
79 filters: { mutationKey: ['addTodo'], status: 'pending' },
80 select: (mutation) => mutation.state.variables,
81})
82```
83β
84[//]: # 'ExampleUI4'
85β
86`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.
87β
88## Via the cache
89β
90When 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.
91β
92To 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.
93β
94### Updating a list of todos when adding a new todo
95β
96[//]: # 'Example'
97β
98```tsx
99const queryClient = useQueryClient()
100β
101useMutation({
102 mutationFn: updateTodo,
103 // When mutate is called:
104 onMutate: async (newTodo) => {
105 // Cancel any outgoing refetches
106 // (so they don't overwrite our optimistic update)
107 await queryClient.cancelQueries({ queryKey: ['todos'] })
108β
109 // Snapshot the previous value
110 const previousTodos = queryClient.getQueryData(['todos'])
111β
112 // Optimistically update to the new value
113 queryClient.setQueryData(['todos'], (old) => [...old, newTodo])
114β
115 // Return a context object with the snapshotted value
116 return { previousTodos }
117 },
118 // If the mutation fails,
119 // use the context returned from onMutate to roll back
120 onError: (err, newTodo, context) => {
121 queryClient.setQueryData(['todos'], context.previousTodos)
122 },
123 // Always refetch after error or success:
124 onSettled: () => {
125 queryClient.invalidateQueries({ queryKey: ['todos'] })
126 },
127})
128```
129β
130[//]: # 'Example'
131β
132### Updating a single todo
133β
134[//]: # 'Example2'
135β
136```tsx
137useMutation({
138 mutationFn: updateTodo,
139 // When mutate is called:
140 onMutate: async (newTodo) => {
141 // Cancel any outgoing refetches
142 // (so they don't overwrite our optimistic update)
143 await queryClient.cancelQueries({ queryKey: ['todos', newTodo.id] })
144β
145 // Snapshot the previous value
146 const previousTodo = queryClient.getQueryData(['todos', newTodo.id])
147β
148 // Optimistically update to the new value
149 queryClient.setQueryData(['todos', newTodo.id], newTodo)
150β
151 // Return a context with the previous and new todo
152 return { previousTodo, newTodo }
153 },
154 // If the mutation fails, use the context we returned above
155 onError: (err, newTodo, context) => {
156 queryClient.setQueryData(
157 ['todos', context.newTodo.id],
158 context.previousTodo,
159 )
160 },
161 // Always refetch after error or success:
162 onSettled: (newTodo) => {
163 queryClient.invalidateQueries({ queryKey: ['todos', newTodo.id] })
164 },
165})
166```
167β
168[//]: # 'Example2'
169β
170You can also use the `onSettled` function in place of the separate `onError` and `onSuccess` handlers if you wish:
171β
172[//]: # 'Example3'
173β
174```tsx
175useMutation({
176 mutationFn: updateTodo,
177 // ...
178 onSettled: (newTodo, error, variables, context) => {
179 if (error) {
180 // do something
181 }
182 },
183})
184```
185β
186[//]: # 'Example3'
187β
188## When to use what
189β
190If 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.
191β
192However, 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.