DEV Community

Cover image for Implementing optimistic UI with Apollo and ReactJS
Rossano D'Angelo
Rossano D'Angelo

Posted on

Implementing optimistic UI with Apollo and ReactJS

Optimistic UI is a pattern that you can use to simulate the results of a mutation and update the UI even before receiving a response from the server. Once the response is received from the server, the optimistic result is thrown away and replaced with the actual result.

This is the definition that Apollo gave to the term "optmistic user interface" on their official documentation.

I recently discovered this concept by attending a course about improving performances of Apollo Client by using caching.

But what kind of benefits does it bring? Does it come without downsides?

Apollo Client without Optimistic UI

Here's a visual example of what happens when we use Apollo Client without the optimistic UI pattern when the user wants to send data to our application (for example, toggling on/off a favourite contact in a cloud based address book).

Without Optimistic UI

This means that the user sees the UI updated only after the server computes the mutation and provides the results. If the datasource experiences delays, the user of our application will have to wait to see the result of his action.

Here's a visual example of what happens when we use Apollo Client without the optimistic UI pattern.

With Optimistic UI

The user sees the UI updating right after the action without waiting for the server to compute the mutation. Apollo Client updates the caches providing an optimistic result: this means that we assume that the result of the mutation is positive and update the UI accordingly.

But what happens if, for any reason, the actual result of the mutation is different than the optimistic result provided? If the request fails, we need to rollback to the previous state because otherwise the user would remain in a non-consistent state.

Example

Here you can observe the delay between the HTTP call and the UI to be updated. That's a classic effect of the Apollo Cache being updated after receiving the data from the data source.

Example without Optimistic UI

Now let's see how this changes applying the optimistic UI pattern - which is very easy to do with Apollo.

Example with Optimistic UI

You can notice how the UI updates right after the click and there isn't any "loading time". In the example above, the communication client cache - server is fast because both are running on my machine. But imagine if the server is hosted somewhere else and there are delays.. The optimistic response "anticipate" the response the server will give you to make the user experience smoother to the user.

Top comments (0)