We'll learn about optimistic updates and add them to our hook's implementation to improve the user experience.
In the previous module, we implemented the
useComments hook, we tested it, and
we saw that it works as expected. However, every time a user adds a comment, we
refetch all the comments from the database. We're making two API requests:
add comment mutation
The latter seems redundant as we already have all the information about the new comment that we need. Also, making an additional call puts the comments section into a loading state. For blog posts with many comments, the page may feel slow. Hence it's not the best user experience.
Wouldn't it be enough to push it to the comments state as we have all the
information? The push is not enough, because we need to handle the
mutation error, but we can improve our hook and enhance the experience. That's
what we're going to do in this lesson!
Introducing optimistic updates#
In an optimistic update, the UI assumes that the change was successful and displays the new state before receiving information from the API. When API returns a confirmation that the call was successful, the UI stays the same. We don't have to do anything unless API gives some additional info. If there was an error, we need to handle it on the frontend and revert the change.
Implementing optimistic updates#
Let's go back to the code editor and open the
useComments.ts file. We'll
Comment type and add a