Performance: Optimistic updates pattern
This pattern affects interaction responsiveness and perceived speed by updating UI before server confirmation.
Jump into concepts and practice - no test required
function handleClick() { setData(prev => ({ ...prev, updated: true })); // update UI immediately fetch('/api/update', { method: 'POST' }).catch(() => { setData(prev => ({ ...prev, updated: false })); // rollback on error }); } <button onClick={handleClick}>Update</button>
async function handleClick() { const response = await fetch('/api/update', { method: 'POST' }); if (response.ok) { setData(await response.json()); } } <button onClick={handleClick}>Update</button>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Waiting for server response before UI update | Multiple DOM updates after async call | Triggers 1 reflow per update delay | Higher paint cost due to delayed changes | [X] Bad |
| Optimistic UI update before server response | Single immediate DOM update | Single reflow triggered instantly | Lower paint cost with smooth interaction | [OK] Good |
optimistic updates pattern in Next.js?setState.setState to update UI, then send API request, revert on error -> Option Cconst [likes, setLikes] = useState(0);
async function handleLike() {
setLikes(likes + 1);
try {
await fetch('/api/like', { method: 'POST' });
} catch {
setLikes(likes); // revert on error
}
}setLikes(likes + 1).setLikes(likes) resets likes to the original value before increment.const [count, setCount] = useState(0);
async function increment() {
setCount(count + 1);
try {
await fetch('/api/increment', { method: 'POST' });
} catch {
setCount(count - 1);
}
}count variable inside catch is the old value before increment.count does not revert to original because count was already incremented in UI.count value inside catch block -> Option A