Optimistic Updates (useOptimistic)
Instant UI feedback that automatically reverts on failure.
Lying to the User (In a Good Way)
useOptimistic is a React Hook that lets you temporarily update your UI with the *expected* result of a mutation before the server has actually confirmed it.
It makes your application feel incredibly fast and responsive, mimicking zero-latency native apps.
The Speed of Perception
If a user clicks a 'Like' button, they don't want to see a loading spinner for 500 milliseconds while the server updates the database.
They expect the heart icon to fill in instantly. If the network request subsequently fails, the UI should gracefully revert back to its original state.
State vs. Optimism
You initialize the hook with the true state: const [optLikes, addOptLike] = useOptimistic(likes, (state, newAmount) => state + newAmount).
Inside your event handler, you first call addOptLike(1) to instantly update the UI. Then, you trigger your Server Action to actually update the database.
The Ghost Reversion
Try the 'Like' button with the Server Error toggle OFF. It feels instant. Now, turn the Server Error toggle ON and click 'Like'. The UI instantly updates (optimistically), but watch how it automatically reverts a second later when the server rejects the request.
Client Component
Gorgeous Sunset
Next.js Server
export async function likePost(id: string) {
await db.post.increment(id);
// If network drops, throws Error
if (networkError) { throw new Error(); }
Console Log
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
useOptimisticinstantly updates the UI before a server mutation finishes.- It prevents the need for loading spinners on micro-interactions (like Upvotes).
- If the server action fails, React automatically reverts the UI to the true state.
- It relies heavily on React Transitions to know when the mutation is complete.
- Next.js Server Actions are automatically wrapped in transitions, making them a perfect pair.
Done with this concept?
Mark it complete to track your progress. No login needed.