Implementing Optimistic Updates Manually
Apply optimistic state locally, queue the mutation, and handle success and failure cases explicitly.
State Before the Mutation
Manual optimistic updates start with local component state initialized from server data: const [items, setItems] = useState(serverItems). This local state is what you render, and it is what you will mutate optimistically. You should NOT mutate server-fetched data directly — keep a local copy you control.
The Optimistic Update Step
When the user triggers a mutation (clicking "Add", "Like", "Delete"), perform the state update immediately before calling the API: setItems(prev => [...prev, newItem]). The UI reflects the change instantly. Only after this update do you fire the actual network request.
All lessons in this course
- What Is Optimistic UI and When to Use It
- Implementing Optimistic Updates Manually
- Rollback on Error and Conflict Resolution
- Optimistic Patterns with React Query and Zustand