Instant UI feedback while a Server Action runs.
Skip to solutionKEEP THE
hardFrontend
How do you do optimistic updates in Next.js (useOptimistic, useActionState)?
960 views
01
Understand the problem
nextjsuseoptimisticuseactionstateserver-actions
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Nudge consolestandby
Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.
03
Study the solution
useOptimistic applies a temporary optimistic state immediately while the Server Action is pending, reverting if it fails. useActionState tracks the action's result and pending status. Together they give responsive forms/mutations with proper rollback.
Solution ready — 2 min read
Classified // press E to declassify
04
Read the code
Optimistic like button
'use client';
import { useOptimistic } from 'react';
import { toggleLike } from './actions';
export function Like({ post }) {
const [likes, addOptimistic] = useOptimistic(post.likes);
return (
<form action={async () => { addOptimistic(likes + 1); await toggleLike(post.id); }}>
<button>♥ {likes}</button> {/* updates instantly, reverts if action fails */}
</form>
);
}05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.
Transmission complete // awaiting log
KEEP THE
STREAK ALIVE.
Dossier 78 of 95 decoded in the Next.js track. One more won't hurt.