Make your App faster using Optimistic Updates (React Query)


In this article, we will discuss what is an optimistic update and how to implement it in your React app to make it feel faster and more responsive, using React Query.
When doing operations that involve waiting for external services, like an API call that will mostly succeed, we proactively update the UI. This approach improves the user experience, making it better and smoother.
Imagine you have a list of todos, and we have to add a delete action in the frontend to remove a todo.
When the users click on delete, we will:
Here is a code example with React Query :
In this example, we use the useMutation hook, which takes:
mutationFn : It takes the async function to delete the todo in the backend.onSuccess : it is called when the mutation is finished, and in this example, we refetch the todos list, so that the deleted todo is removed from the UI.When the users click on delete, we will :
Unlike the first approach, the deletion of the todo will look like it's instant since we won't wait for the API call response to update the UI.
The code with an optimistic update :
We added onMutate which will take the todoToDeleteId, it will be executed before the mutation is happening (in this case, delete todo).
We added an onError callback, which is called in case of failure. It utilizes the context returned to roll back to the old data.
Additionally, we removed the onSuccess callback since we have already removed the todo from the UI and won't need to refetch.
You may want to acknowledge the user about the success or failure of the deletion to enhance the user experience. For instance, by displaying a toast notification for both error and success scenarios.
In a nutshell, optimistic updates make your application feel faster. It's like a quick tweak to the user interface before the backend responds, ensuring a smoother user experience.
Consider adding optimistic updates to your code for a more visually responsive interface and the impression of smoother app performance.
Many Thanks to Ali Guedda for reviewing this article.
Thank you for reading, and happy coding!
Get notified when we publish new blog posts