Senior LevelReact JS & React 19
How does useOptimistic handle complex multi-step rollback workflows when network mutations fail?
❓ Interview Prompt: Explain React 19 `useOptimistic`, rollback mechanics, handling network failure exceptions, and temporary state cleanup.
In React 19, 'useOptimistic' handles state rollbacks automatically when Server Actions fail:
Rollback Mechanics:
1
'useOptimistic' state is ephemeral and bound strictly to the pending lifecycle of the wrapped Server Action Promise.
2
When the Server Action Promise resolves successfully, React replaces optimistic state with actual server state.
3
If the Server Action Promise rejects or throws an error, React automatically discards the optimistic state and reverts to true server state!
Code Implementation Example
jsx
function LikeButton({ initialLikes, likeAction }) {
const [optimisticLikes, setOptimisticLikes] = useOptimistic(
initialLikes,
(current, delta) => current + delta
);
async function handleLike() {
setOptimisticLikes(1); // 1. Optimistic +1 update
try {
await likeAction(); // 2. Async Server Action
} catch (err) {
// 3. If action throws, React automatically rolls back to initialLikes!
toast.error('Failed to like post');
}
}
}💡Automatic state rollback handling in React 19 useOptimistic.
🎯 Interview Key Takeaway
React 19's useOptimistic automatically rolls back ephemeral UI updates if the underlying Server Action fails.
#React 19#useOptimistic#Rollback#Senior
Back to all React JS & React 19 Questions→