Beginner LevelReact JS & React 19
How does the useOptimistic hook in React 19 render instant UI updates before server confirmation?
❓ Interview Prompt: Explain React 19 `useOptimistic`, Optimistic UI pattern, instantaneous user feedback, and automatic rollback on failure.
'useOptimistic' is a native React 19 hook that enables Optimistic UI updates:
How It Works:
1
Displays immediate optimistic state to the user while an async operation (like a Server Action) is in-flight.
2
When the async operation finishes, React automatically replaces the optimistic state with the actual server response.
3
If the server action fails or throws, React automatically rolls back to the original state!
Code Implementation Example
jsx
import { useOptimistic, useState } from 'react';
function MessageList({ messages, sendMessageAction }) {
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(current, newMessage) => [...current, { text: newMessage, sending: true }]
);
async function handleFormSubmit(formData) {
const text = formData.get('message');
addOptimisticMessage(text); // 1. Instant UI update!
await sendMessageAction(text); // 2. Async server action
}
return (
<form action={handleFormSubmit}>
{optimisticMessages.map((m, i) => (
<div key={i}>{m.text} {m.sending && '(Sending...)'}</div>
))}
<input name="message" />
</form>
);
}💡Rendering instant UI updates with automatic rollback using React 19 useOptimistic.
🎯 Interview Key Takeaway
useOptimistic provides responsive UI by displaying expected state changes immediately while network operations complete.
#React 19#useOptimistic#Optimistic UI#Beginner
Back to all React JS & React 19 Questions→