How would you implement optimistic state updates for a feature like a like button, so the interface feels instant while a server action processes the actual update?
Short answer
You use the useOptimistic hook to immediately show the expected new state, such as an increased like count, right when the user clicks, while the actual server action runs in the background, and React automatically reconciles the optimistic value with the real result once the…
Advertisement
AModel answer
You use the useOptimistic hook to immediately show the expected new state, such as an increased like count, right when the user clicks, while the actual server action runs in the background, and React automatically reconciles the optimistic value with the real result once the server action completes or fails.
'use client';
import { useOptimistic } from 'react';
function LikeButton({ likes, onLike }) {
const [optimisticLikes, addOptimisticLike] = useOptimistic(likes, (state) => state + 1);
return (
<button onClick={() => { addOptimisticLike(); onLike(); }}>
{optimisticLikes} likes
</button>
);
}Real-world example
A social media app shows a like count increasing immediately when a user taps the like button, well before the server action finishes saving that like to the database, making the interaction feel instant and responsive.
Likely follow-ups
- What happens to the optimistic state if the server action ultimately fails?
- How does useOptimistic compare to manually managing a temporary loading state?
Related topics