javascript / expert
Snippet
Atomic Optimistic UI with useOptimistic for Multi-Step Transitions
Use the useOptimistic hook to provide immediate visual feedback during Server Action execution. This pattern maintains a deterministic sync between the temporary UI state and the eventual server response, enhancing perceived performance.
snippet.js
1
2
3
4
5
6
7
8
const [optimisticState, addOptimistic] = useOptimistic(state,(currentState, newValue) => ({...currentState,...newValue,isPending: true}));
nextjs
Breakdown
1
useOptimistic(state, reducer)
Hook that manages a temporary state during an async transition.
2
(currentState, newValue) => ...
The reducer logic that defines how the optimistic update merges with existing state.
3
isPending: true
Flag used to visually distinguish optimistic data from verified server data.