Optimistic UI Updates with React useOptimistic Hook0%
Optimistic UI Updates with React useOptimistic Hook
Beginner12 min read•Updated: Jul 11, 2026
Optimistic UI Updates with React useOptimistic Hook
In high-performance web applications, waiting 500ms for a backend database write before updating the UI feels sluggish. Optimistic UI Updates provide instantaneous visual feedback by updating the UI immediately under the assumption that the server request will succeed, and rolling back gracefully if an error occurs. React 19 and Next.js 15 provide the official useOptimistic hook for this pattern.
1. What is useOptimistic?
The useOptimistic hook lets you show a different state while an async action is in flight:
- 1User clicks "Like" or submits a message.
- 2The UI updates instantly ($0\text{ms}$ delay) with temporary optimistic data.
- 3The Server Action runs in the background.
- 4Once the server responds, the optimistic state is replaced by the actual persistent state.
- 5If the server throws an error, the UI rolls back to the original state automatically!
2. Implementing Optimistic Course Likes
TSX
// components/CourseLikeButton.tsx
'use client';
import { useOptimistic, useTransition } from 'react';
import { toggleCourseLikeAction } from '@/app/actions/like-actions';
interface LikeProps {
courseId: string;
initialLikes: number;
initialHasLiked: boolean;
}
export default function CourseLikeButton({
courseId,
initialLikes,
initialHasLiked
}: LikeProps) {
const [isPending, startTransition] = useTransition();
// Optimistic State definition
const [optimisticState, setOptimisticState] = useOptimistic(
{ likes: initialLikes, hasLiked: initialHasLiked },
(current, update: boolean) => ({
likes: update ? current.likes + 1 : current.likes - 1,
hasLiked: update
})
);
const handleToggle = () => {
const nextLikedState = !optimisticState.hasLiked;
// 1. Immediately update UI state optimistically!
startTransition(async () => {
setOptimisticState(nextLikedState);
try {
// 2. Perform actual server mutation in background
await toggleCourseLikeAction(courseId, nextLikedState);
} catch (error) {
console.error('Failed to update like status on server:', error);
// React automatically rolls back the optimistic state upon transition failure!
}
});
};
return (
<button
onClick={handleToggle}
className={`px-4 py-2 rounded-lg font-semibold transition-all ${
optimisticState.hasLiked
? 'bg-rose-500 text-white'
: 'bg-slate-100 text-slate-700 hover:bg-slate-200'
}`}
>
❤️ {optimisticState.likes} Likes
</button>
);
}
Interactive Quiz
Multiple Choice Questions
Question 1
What is the primary purpose of an Optimistic UI update in web applications?
Question 2
Which React hook manages optimistic state during asynchronous transitions?
Question 3
What happens if the background Server Action fails or throws an unhandled error during an optimistic update?
Question 4
Which hook is typically paired with
useOptimistic to manage the asynchronous execution lifecycle?Question 5
Why is Optimistic UI particularly beneficial for social media actions like Likes, Upvotes, and Bookmark toggles?
Next Lesson
API Route Handlers (route.ts): Building RESTful Microservices
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.