Optimistic Updates in React: UX That Feels Instant
Why Your UI Feels Slow User clicks 'Like'. Nothing happens for 300ms. Button finally changes state. That 300ms delay is your network round-trip. The server almost certainly succeeded. But the UI wa...
Source: dev.to
Why Your UI Feels Slow User clicks 'Like'. Nothing happens for 300ms. Button finally changes state. That 300ms delay is your network round-trip. The server almost certainly succeeded. But the UI waited anyway. Optimistic updates flip this: assume success, update immediately, rollback if wrong. The Pattern // Before: wait for server async function likePost(postId: string) { const response = await fetch(`/api/posts/${postId}/like`, { method: 'POST' }); const updated = await response.json(); setPosts(posts.map(p => p.id === postId ? updated : p)); } // After: update immediately, sync in background async function likePost(postId: string) { // 1. Update UI immediately setPosts(posts.map(p => p.id === postId ? { ...p, likes: p.likes + 1, liked: true } : p )); try { // 2. Sync with server await fetch(`/api/posts/${postId}/like`, { method: 'POST' }); } catch (error) { // 3. Rollback on failure setPosts(posts.map(p => p.id === postId ? { ...p, likes: p.likes - 1, liked: false } : p ));