React 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.
Via the UI #
This is the simpler variant, as it doesn't interact with the cache directly.
1const addTodoMutation = useMutation({
2 mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
3 // make sure to _return_ the Promise from the query invalidation
4 // so that the mutation stays in `pending` state until the refetch is finished
5 onSettled: async () => {
6 return await queryClient.invalidateQueries({ queryKey: ['todos'] })
7 },
8})
9
10const { isPending, submittedAt, variables, mutate, isError } = addTodoMutation
you 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
:
1<ul>
2 {todoQuery.items.map((todo) => (
3 <li key={todo.id}>{todo.text}</li>
4 ))}
5 {isPending && <li style={{ opacity: 0.5 }}>{variables}</li>}
6</ul>
We'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.
If 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:
1{
2 isError && (
3 <li style={{ color: 'red' }}>
4 {variables}
5 <button onClick={() => mutate(variables)}>Retry</button>
6 </li>
7 )
8}
If the mutation and the query don't live in the same component #
This 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
:
1// somewhere in your app
2const { mutate } = useMutation({
3 mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
4 onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
5 mutationKey: ['addTodo'],
6})
7
8// access variables somewhere else
9const variables = useMutationState<string>({
10 filters: { mutationKey: ['addTodo'], status: 'pending' },
11 select: (mutation) => mutation.state.variables,
12})
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.
Via the cache #
When 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.
To 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.
Updating a list of todos when adding a new todo #
1const queryClient = useQueryClient()
2
3useMutation({
4 mutationFn: updateTodo,
5 // When mutate is called:
6 onMutate: async (newTodo) => {
7 // Cancel any outgoing refetches
8 // (so they don't overwrite our optimistic update)
9 await queryClient.cancelQueries({ queryKey: ['todos'] })
10
11 // Snapshot the previous value
12 const previousTodos = queryClient.getQueryData(['todos'])
13
14 // Optimistically update to the new value
15 queryClient.setQueryData(['todos'], (old) => [...old, newTodo])
16
17 // Return a context object with the snapshotted value
18 return { previousTodos }
19 },
20 // If the mutation fails,
21 // use the context returned from onMutate to roll back
22 onError: (err, newTodo, context) => {
23 queryClient.setQueryData(['todos'], context.previousTodos)
24 },
25 // Always refetch after error or success:
26 onSettled: () => {
27 queryClient.invalidateQueries({ queryKey: ['todos'] })
28 },
29})
Updating a single todo #
1useMutation({
2 mutationFn: updateTodo,
3 // When mutate is called:
4 onMutate: async (newTodo) => {
5 // Cancel any outgoing refetches
6 // (so they don't overwrite our optimistic update)
7 await queryClient.cancelQueries({ queryKey: ['todos', newTodo.id] })
8
9 // Snapshot the previous value
10 const previousTodo = queryClient.getQueryData(['todos', newTodo.id])
11
12 // Optimistically update to the new value
13 queryClient.setQueryData(['todos', newTodo.id], newTodo)
14
15 // Return a context with the previous and new todo
16 return { previousTodo, newTodo }
17 },
18 // If the mutation fails, use the context we returned above
19 onError: (err, newTodo, context) => {
20 queryClient.setQueryData(
21 ['todos', context.newTodo.id],
22 context.previousTodo,
23 )
24 },
25 // Always refetch after error or success:
26 onSettled: (newTodo) => {
27 queryClient.invalidateQueries({ queryKey: ['todos', newTodo.id] })
28 },
29})
You can also use the onSettled
function in place of the separate onError
and onSuccess
handlers if you wish:
1useMutation({
2 mutationFn: updateTodo,
3 // ...
4 onSettled: (newTodo, error, variables, context) => {
5 if (error) {
6 // do something
7 }
8 },
9})
When to use what #
If 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.
However, 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.