javascript / expert
Snippet
Optimistic UI Updates with useOptimistic
The useOptimistic hook allows Next.js applications to immediately reflect server mutations in the UI before the Server Action completes. It tracks a temporary state that is automatically discarded once the parent component re-renders with the actual server-validated data.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { useOptimistic } from 'react';export function CommentList({ comments, addCommentAction }) {const [optimisticComments, addOptimisticComment] = useOptimistic(comments,(state, newComment) => [...state, { text: newComment, sending: true }]);async function action(formData: FormData) {const comment = formData.get('comment') as string;addOptimisticComment(comment);await addCommentAction(comment);}return (<form action={action}>{optimisticComments.map((c, i) => (<div key={i} style={{ opacity: c.sending ? 0.5 : 1 }}>{c.text}</div>))}<input name="comment" /><button type="submit">Post</button></form>);}
nextjs
Breakdown
1
useOptimistic(comments, (state, newComment) => ...)
Initializes optimistic state based on existing comments and defines the update logic.
2
addOptimisticComment(comment)
Triggers the immediate UI change while the background async action is still pending.