javascript / expert
Snippet
Optimistische UI-Updates mit useOptimistic
Der useOptimistic-Hook ermöglicht es Next.js-Anwendungen, Server-Mutationen sofort in der UI widerzuspiegeln, bevor die Server Action abgeschlossen ist. Er verwaltet einen temporären Status, der automatisch verworfen wird, sobald die übergeordnete Komponente mit den tatsächlichen, vom Server validierten Daten neu gerendert wird.
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
Erklärung
1
useOptimistic(comments, (state, newComment) => ...)
Initialisiert den optimistischen Status basierend auf vorhandenen Kommentaren und definiert die Update-Logik.
2
addOptimisticComment(comment)
Löst die sofortige UI-Änderung aus, während die asynchrone Hintergrundaktion noch läuft.