useOptimistic is a React hook that enables you to show immediate UI feedback for user interactions before server confirmation. It enhances user experience by making apps feel responsive while actual data operations happen in background.
Syntax: const [optimisticState, addOptimistic] = useOptimistic(state, updateFn);
Key benefits:
Simple example:
function LikeButton({ postId, likes }) {
const [optimisticLikes, addOptimistic] = useOptimistic(likes, (current, delta) => current + delta);
const handleLike = async () => {
addOptimistic(1); // Immediate visual update
await likePost(postId); // Actual server call
};
return <button onClick={handleLike}>❤️ {optimisticLikes}</button>;
}
The useOptimistic
hook is a powerful React feature that helps create responsive user interfaces by showing immediate feedback for user actions, even before server operations complete. This technique, known as “optimistic UI”, makes applications feel faster and more responsive.
The hook takes two parameters:
When you call the addOptimistic
function:
Perfect for like buttons, comment forms, and reaction systems where immediate feedback improves user experience.
Show form as submitted immediately while actual submission happens in background.
Update item quantities instantly while syncing with server.
Mark items as complete immediately without waiting for server confirmation.
function TodoItem({ todo }) {
const [optimisticTodo, updateOptimistic] = useOptimistic(
todo,
(current, updates) => ({ ...current, ...updates })
);
const toggleComplete = async () => {
updateOptimistic({ completed: !todo.completed });
await updateTodo(todo.id, { completed: !todo.completed });
};
return (
<div>
<input
type="checkbox"
checked={optimisticTodo.completed}
onChange={toggleComplete}
/>
<span>{optimisticTodo.text}</span>
</div>
);
}
✅ Best for:
❌ Avoid for:
The useOptimistic hook is an excellent tool for creating modern, responsive React applications. When used appropriately, it significantly enhances user experience by eliminating wait times for common interactions.
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪