Ask anything about this article
Hi! I've read this article.
What would you like to know?
@farhan

User experience is defined by latency. When a user clicks a "Like" button, they expect immediate visual feedback. If they have to wait 300ms for a network request to round-trip to the server and back before the heart turns red, your app feels sluggish and broken.
The solution is Optimistic UI.
Optimistic UI means we assume the server request will succeed. We instantly update the UI state, fire the network request in the background, and only revert the UI if the network request fails.
Here is a simplified version of a robust Optimistic Like Button using React state:
tsximport { useState } from 'react';
export default function LikeButton({ initialLikes, blogId }) {
const [likes, setLikes] = useState(initialLikes);
const [hasLiked, setHasLiked] = useState(false);
const handleLike = async () => {
// 1. Optimistic Update (Immediate Feedback)
setLikes(prev => prev + 1);
setHasLiked(true);
try {
// 2. Network Request (Background)
const res = await fetch('/api/like', { method: 'POST', body: JSON.stringify({ blogId }) });
if (!res.ok) throw new Error('Failed');
} catch (error) {
// 3. Rollback on Failure
console.error("Failed to like post, rolling back.");
setLikes(prev => prev - 1);
setHasLiked(false);
}
};
return (
<button onClick={handleLike} className={hasLiked ? 'text-pink-500' : 'text-gray-500'}>
♥ {likes}
</button>
);
}
While the code above works, production apps need to handle edge cases:
localStorage or tie it to an authenticated user session in the database.By prioritizing optimistic updates, you mask network latency and create a native-app-like experience on the web.