implementing-optimistic-updates
Optimistic UI Updates with useOptimistic
- Shows anticipated result immediately
- Reverts to actual state when async completes
- Provides better UX than waiting for server
- Works with
startTransitionfor async operations
import { useOptimistic, startTransition } from 'react';
function MessageList({ messages, sendMessage }) {
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(state, newMessage) => [...state, { ...newMessage, sending: true }]
);
const handleSend = async (text) => {
addOptimisticMessage({ id: Date.now(), text });
startTransition(async () => {
await sendMessage(text);
});
};
return (
<ul>
{optimisticMessages.map((msg) => (
<li key={msg.id}>
{msg.text} {msg.sending && <small>(Sending...)</small>}
</li>
))}
</ul>
);
}
function LikeButton({ postId, initialLikes }) {
const [optimisticLikes, addOptimisticLike] = useOptimistic(
initialLikes,
(state, amount) => state + amount
);
const handleLike = async () => {
addOptimisticLike(1);
startTransition(async () => {
await fetch(`/api/posts/${postId}/like`, { method: 'POST' });
});
};
return (
<button onClick={handleLike}>
❤️ {optimisticLikes}
</button>
);
}
For comprehensive useOptimistic documentation, see: research/react-19-comprehensive.md lines 182-240.
NEVER
- Mutate state directly in update function
- Use for critical operations that must succeed
- Skip error handling for failed optimistic updates
If handling Prisma transaction errors in optimistic updates, use the handling-transaction-errors skill from prisma-6 for graceful P-code error handling.
More from djankies/claude-configs
optimizing-with-react-compiler
Teaches what React Compiler handles automatically in React 19, reducing need for manual memoization. Use when optimizing performance or deciding when to use useMemo/useCallback.
16reviewing-prisma-patterns
Review Prisma code for common violations, security issues, and performance anti-patterns found in AI coding agent stress testing. Use when reviewing Prisma Client usage, database operations, or performing code reviews on projects using Prisma ORM.
8migrating-from-v3
Migrate from Tailwind CSS v3 to v4 including configuration migration (JS to CSS), utility renames, opacity changes, and color system updates. Use when upgrading existing projects to v4.
6implementing-query-pagination
Implement cursor-based or offset pagination for Prisma queries. Use for datasets 100k+, APIs with page navigation, or infinite scroll/pagination mentions.
5using-reducers
Teaches useReducer for complex state logic in React 19. Use when state updates depend on previous state, multiple related state values, or complex update logic.
5implementing-code-splitting
Teaches code splitting with lazy() and Suspense in React 19 for reducing initial bundle size. Use when implementing lazy loading, route-based splitting, or optimizing performance.
5