javascript / intermediate
Snippet
Optimistic UI Updates with useOptimistic
The useOptimistic hook allows you to show a different state while an async action (like a Server Action) is pending. This makes the UI feel significantly faster by immediately rendering the expected result before the server confirms it.
snippet.js
1
2
3
4
5
6
7
8
9
10
const [optimisticMessages, addOptimisticMessage] = useOptimistic(messages,(state, newMessage) => [...state, { text: newMessage, sending: true }]);async function action(formData) {const message = formData.get('message');addOptimisticMessage(message);await sendMessage(message);}
nextjs
Breakdown
1
useOptimistic(messages, ...)
Initializes the optimistic state with the current server-side messages.
2
(state, newMessage) => [...state, ...]
Defines how the UI should look while the transition is pending.
3
addOptimisticMessage(message)
Triggers the immediate UI update before the actual server request finishes.