0 day streak
javascript / intermediate
Snippet

Optimistic UI Updates with useOptimistic

The useOptimistic hook provides a way to update the UI immediately before a server operation completes, improving perceived performance.

snippet.js
javascript
1
2
3
4
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(state, newMessage) => [...state, { text: newMessage, sending: true }]
);
nextjs
Breakdown
1
useOptimistic(messages, ...)
Initializes the optimistic state with the current server-provided messages.
2
(state, newMessage) => [...state, ...]
The reducer function that defines how the optimistic state is updated during a pending action.