Optimistic Updates for Immediate UI Feedback
Shows how to perform optimistic updates to the UI when mutating data, ensuring immediate feedback to users while the mutation request is in progress.
import { useMutation, useQueryClient } from 'react-query';
// Mock function to simulate adding a todo item
async function addTodoAPI(todo) {
// Here you'd have an API call to add a todo
return { id: Date.now(), ...todo };
}
First, we import the necessary functions from react-query and define a mock API function to simulate adding a todo item. This function would typically make an actual API call to add an item to a database.
const AddTodo = () => {
const queryClient = useQueryClient();
const { mutate } = useMutation(addTodoAPI, {
onMutate: async newTodo => {
await queryClient.cancelQueries('todos');
const previousTodos = queryClient.getQueryData('todos');
queryClient.setQueryData('todos', old => [...old, newTodo]);
return { previousTodos };
},
onError: (err, newTodo, context) => {
queryClient.setQueryData('todos', context.previousTodos);
},
onSettled: () => {
queryClient.invalidateQueries('todos');
},
});
const addTodo = () => {
mutate({ text: 'New Todo', completed: false });
};
return <button onClick={addTodo}>Add Todo</button>;
};
This react component uses the useMutation hook to perform an optimistic update. When adding a todo, the UI immediately reflects this new item before the mutation is confirmed. If the API call fails, the onError option rolls back the optimistic update.