The useOptimistic hook enables optimistic UI updates that show immediately while async operations complete. Here's how to use it.
Basic Usage#
Like Button#
Message Sending#
Delete with Undo#
Form Submission#
Toggle with Multiple States#
Cart Updates#
Error Handling#
Batch Operations#
Best Practices#
When to Use:
✓ Likes/favorites/bookmarks
✓ Adding items to lists
✓ Form submissions
✓ Toggle states
✓ Real-time updates
Patterns:
✓ Show pending state visually
✓ Handle errors gracefully
✓ Revert on failure
✓ Use with server actions
Visual Feedback:
✓ Reduce opacity for pending
✓ Show loading indicators
✓ Disable during update
✓ Clear error states
Avoid:
✗ Critical data without confirmation
✗ Complex multi-step operations
✗ Operations that can't be reverted
✗ Ignoring error states
Conclusion#
The useOptimistic hook provides immediate UI feedback while async operations complete in the background. Use it for actions like likes, adding items, and form submissions where instant feedback improves perceived performance. Always provide visual indicators for pending states and handle errors gracefully by reverting the UI when operations fail. Combine with server actions for a seamless optimistic update pattern.