Optimistic UI Updates
Optimistic updates change the interface immediately while the server operation is still running. They are useful when the expected operation is fast and reversible, such as liking a post or toggling a setting.
The UI should have a recovery strategy if the server rejects the mutation. Optimistic UI without error handling can create a mismatch between what the user sees and what the database contains.
Optimistic Interaction
'use client';
import { useOptimistic } from 'react';
export function LikeButton({ liked }: { liked: boolean }) {
const [optimisticLiked, setOptimisticLiked] = useOptimistic(liked);
return (
<button onClick={() => setOptimisticLiked(!optimisticLiked)}>
{optimisticLiked ? 'Unlike' : 'Like'}
</button>
);
}The optimistic state allows the interface to respond immediately while the server mutation is processed.
Key Takeaways
Optimistic updates improve perceived responsiveness.
Always design a failure or rollback strategy.
Use optimistic behavior for operations where temporary assumptions are acceptable.