Optimistic vs pessimistic updates
When a user clicks a button, you have two options. Wait for the server to confirm and then update the UI. Or update the UI immediately and reconcile when the server responds. The first feels slow. The second feels instant. Both are valid, and the right choice depends on the cost of being wrong.
Optimistic updates are perfect for low-risk actions: liking a post, adding to cart, marking a task done. If the server rejects, you roll back and show an error. Pessimistic updates are better for anything where a wrong guess is embarrassing: bank transfers, medical records, deleting something permanent. Wait for confirmation, show a spinner, then update.
async function addToCart(bookId) {
const button = document.querySelector('[data-id="' + bookId + '"] button');
const originalText = button.textContent;
// Optimistic: update UI immediately
button.textContent = 'Added';
button.disabled = true;
try {
const res = await fetch('/api/cart', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ bookId }),
});
if (!res.ok) throw new Error('server rejected');
} catch (err) {
// Rollback on failure
button.textContent = originalText;
button.disabled = false;
showError('Could not add to cart. Try again.');
}
}An optimistic cart update with rollback on failure.
Rollbacks are client-side state reverts, which basically cannot fail. The bigger risk is that the rollback leaves the UI in a state that does not match reality. Always pair optimistic updates with a clear error message so the user knows something did not go through and can retry.
Quiz: Quiz
Loading practice…