javascript / expert
Snippet
Implementing Optimistic Updates with useOptimistic
The useOptimistic hook allows the UI to reflect changes immediately, assuming the server operation will succeed. This pattern significantly improves perceived performance by removing the 'wait time' between a user action and the UI update.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
'use client';import { useOptimistic } from 'react';export function CommentSection({ comments }: { comments: string[] }) {const [optimisticComments, addOptimisticComment] = useOptimistic(comments,(state, newComment: string) => [...state, newComment]);async function action(formData: FormData) {const text = formData.get('text') as string;addOptimisticComment(text);await saveComment(text);}return (<form action={action}>{optimisticComments.map(c => <div key={c}>{c}</div>)}<input name="text" /></form>);}
nextjs
Breakdown
1
useOptimistic(comments, (state, newComment) => ...)
Sets up the temporary state that reverts if the action fails or when the server revalidates.
2
addOptimisticComment(text);
Triggers the immediate UI change before the network request finishes.