typescriptadvanced
Optimistic List with Rollback
A list component that immediately reflects mutations and rolls back on server error.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useState, useCallback } from 'react';
interface Item {
id: string;
text: string;
}
export function useOptimisticList(initial: Item[]) {
const [items, setItems] = useState(initial);
const addItem = useCallback(async (item: Item, serverFn: () => Promise<void>) => {
setItems(prev => [...prev, item]);
try {
await serverFn();
} catch {
setItems(prev => prev.filter(i => i.id !== item.id));
throw new Error('Failed to add item');
}
}, []);
const removeItem = useCallback(async (id: string, serverFn: () => Promise<void>) => {
const backup = items;
setItems(prev => prev.filter(i => i.id !== id));
try {
await serverFn();
} catch {
setItems(backup);
throw new Error('Failed to remove item');
}
}, [items]);
return { items, addItem, removeItem };
}Use Cases
- Todo lists
- Real-time collaborative editing
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptadvanced
Virtualized List Component
Render large lists efficiently by only rendering visible items with calculated scroll positioning.
Best for: Rendering 10k+ item lists
#virtualization#performance
typescriptintermediate
Drag & Drop Sortable List
Reorder list items with native HTML drag and drop events — no external library required.
Best for: Task board reordering
#drag-drop#sortable
typescriptadvanced
React Optimistic Update Pattern
Implement optimistic UI updates that show changes immediately and rollback on server failure.
Best for: Instant UI feedback for server operations
#react#optimistic-ui
typescriptintermediate
useMutation Hook for Side Effects
Handle mutations (POST/PUT/DELETE) with loading, error, reset, and optimistic update support.
Best for: Form submission handling
#react#hooks