Optimistic Updates Pattern
You'll learn how to combine useActionState with useOptimistic to give users instant feedback while the server processes their request in the background.
The Core Problem
When users submit forms or trigger actions, waiting for server confirmation creates a sluggish experience. They click "Like" and... nothing happens for a second. That delay feels broken, even when everything works perfectly.
The Optimistic Pattern
The optimistic updates pattern shows the expected result immediately, then reconciles with reality when the server responds. It's like ordering at a restaurant: the waiter writes down your order right away (optimistic), even though the kitchen hasn't confirmed it yet (server).
import { useActionState, useOptimistic } from 'react';
function LikeButton({ postId, initialLikes }) {
const [state, action, isPending] = useActionState(
async (prevState, formData) => {
const result = await likePost(postId);
return { likes: result.likes };
},
{ likes: initialLikes }
);
const [optimisticLikes, setOptimisticLikes] = useOptimistic(
state.likes,
(current) => current + 1
);
return (
<form action={action} onSubmit={() => setOptimisticLikes()}>
<button>{optimisticLikes} ❤️</button>
</form>
);
}
When the user clicks, optimisticLikes increments instantly. Meanwhile, useActionState handles the server request. If it succeeds, state.likes updates and matches the optimistic value. If it fails, the UI reverts to the real server count.
Why This Combination Works
useActionState manages the server lifecycle (pending, success, error). useOptimistic manages the UI prediction. Together, they create responsive interfaces that feel instant but stay truthful.
Key Takeaway: The optimistic updates pattern combines useActionState for server coordination with useOptimistic for instant UI feedback, creating interfaces that feel immediate while remaining honest about server state.