Building Instant Feedback with useOptimistic
Explore how to implement instant feedback in React forms by using the useOptimistic hook. This lesson helps you understand optimistic UI updates, allowing users to see immediate changes while asynchronous actions finalize in the background. You'll build interactive comment and like features that update instantly and reconcile gracefully with server responses, improving perceived performance and user engagement.
A responsive interface keeps users engaged. They should see their actions reflected immediately, without waiting for background processes to complete. Traditionally, we’d update the state only after the server responds. React 19 introduces the useOptimistic hook, which lets us optimistically update the UI first — showing instant feedback — and then merge in the real result when it arrives, or roll back gracefully if the operation fails.
Concept: What useOptimistic does
useOptimistic lets us derive an optimistic state from our base state while an action is pending.
const [optimisticValue, addOptimisticValue] = useOptimistic(baseValue,(current, pendingUpdate) => /* return new optimistic state */);
baseValueis our source of truth (e.g., comments from server or parent state).optimisticValueis what we render immediately.addOptimisticValue(update)applies a temporary change (e.g., add a pending comment).When our async action resolves, we update base state; React re-derives the optimistic view from the new base. ...