React Hooks
React useOptimistic Hook
useOptimistic shows a provisional UI state while an asynchronous action is still running, then reverts automatically if the action fails. It is designed for the "show it as done, fix it if the server disagrees" pattern.
What is useOptimistic Hook in React?
useOptimistic shows a provisional UI state while an asynchronous action is still running, then reverts automatically if the action fails. It is designed for the "show it as done, fix it if the server disagrees" pattern.
Why useOptimistic Hook matters
A like button or a message send feels instant when the change appears immediately. Writing that by hand means manual rollback logic in every failure path; this hook does the reverting for you.
useOptimistic Hook example
const [optimisticMessages, addOptimistic] = useOptimistic(
messages,
(state, newMessage) => [...state, { text: newMessage, sending: true }]
);
async function handleSend(formData) {
const text = formData.get('text');
addOptimistic(text); // appears instantly
await sendMessage(text); // if this throws, React reverts
}Key points to remember
- React 19, intended to pair with actions and form submissions.
- The reducer describes how to apply the optimistic change to the current state.
- Reversion is automatic when the action fails — no manual rollback.
Common mistakes with useOptimistic Hook
- Using it for state with no asynchronous action behind it.
- Forgetting to mark optimistic items visually, so users cannot tell what is confirmed.
React useOptimistic Hook— Interview Questions & FAQs
What happens if the server request fails?+
React discards the optimistic state and re-renders with the real state, so the UI reverts on its own. Show your own error message from the catch block.
