UseOptimistic and instant feedback
useOptimistic is a React hook that lets you apply a predicted update to state while a real mutation is in flight. If the mutation succeeds, the prediction matches reality. If it fails, React rolls the optimistic state back to the server state automatically.
'use client';
import { useOptimistic } from 'react';
import { toggleLike } from '../actions';
export function LikeButton({ postId, liked }: { postId: number; liked: boolean }) {
const [optimisticLiked, setOptimisticLiked] = useOptimistic(
liked,
(_current, newValue: boolean) => newValue,
);
async function handleClick() {
setOptimisticLiked(!optimisticLiked); // predict
await toggleLike(postId); // real server action
}
return (
<button onClick={handleClick}>
{optimisticLiked ? 'Liked' : 'Like'}
</button>
);
}A like button that flips instantly and reconciles with the server action.
Read the click handler. We flip the optimistic state immediately, then await the real Server Action. The UI feels instant. If the server action throws, React reverts to the last real value it knows. No manual rollback logic, no state management complexity, just a hook and a pure update function.
Quiz: Quiz
Loading practice…