Optimistic UI
"I want to lie to the user", I told my colleagues.
Last Friday, I ran into a tricky UI problem, and I've been wanting to share the solution I came up with after brainstorming with my colleagues.
The Problem
I have two buttons: Like and Dislike. A request to the backend is made when the page loads, fetching the current status (whether the item is liked or disliked). If the status is "disliked", and the user clicks the Like button, the Dislike button should no longer be in the "active" state. Anytime either of these buttons is clicked, a PATCH request is made to update the status.
The Challenge
Here’s the issue: users won’t know if their Like or Dislike action has been successfully processed until the request completes and the page reloads. In the meantime, users might keep clicking the button, bombarding the backend with repeated requests. That’s frustrating.
So, I stood up from my seat and told Adeyanju Tomide and Chioma Ezezim , “How can I lie to the users?”
The Solution
That’s where Optimistic UI comes into play.
Optimistic UI is a technique that allows you to "fake" the update for the user interface, making it seem like the request was successful immediately, even though the request is still processing in the background.
Recommended by LinkedIn
But What If the Request Fails?
That led us to the next question: What happens if the request fails?
Here are some of the approaches I considered:
The Outcome
Even though I initially used useState to manage local UI updates, moving toward TanStack Query’s Optimistic Update API is a cleaner and more scalable solution when working with server data, and I will be updating the codebase soon. Or when do you think I should stick to my current solution?
If you’ve run into similar UI problems, I’d love to hear how you approached them. Do you have any better suggestions for handling such cases?
#frontend #react #optimisticUI #userexperience #tanstackquery #webdevelopment
Thanks for sharing, Samson