Basic Optimistic UI
Purpose
This subtopic addresses how to implement an optimistic UI update pattern using the core SWR hook and React state. It focuses on the common problem of latency in remote mutations—where users want immediate feedback on their actions (e.g., adding a to-do item) without waiting for the server response. By optimistically updating the UI with the expected new state and later reconciling with the server response, the user experience feels faster and more responsive.
Unlike the Immer-based Optimistic UI example, which emphasizes immutable data handling via Immer, this approach uses plain React state and SWR’s built-in mutation features to achieve optimistic updates simply and effectively.
Functionality
The key workflow in this subtopic is centered around the mutate function returned by the useSWR hook:
Initial Data Fetch
useSWR('/api/todos', fetch) fetches the full list of to-do items and caches it.User Action: Add To-Do
When a user submits a new to-do item, the app immediately updates the local cache to include this new item, without waiting for the server:await mutate( fetch('/api/todos', { method: 'POST', body: JSON.stringify(newTodo) }), { optimisticData: [...data, newTodo], rollbackOnError: true, populateCache: newItem => [...data, newItem], revalidate: true } )optimisticData: The local cache is updated instantly with the new to-do appended. This provides immediate UI feedback.rollbackOnError: If the server mutation fails, SWR automatically rolls back to the previous cached data.populateCache: When the server responds with the newly created item (capitalized text), this function merges it into the existing cached list, replacing the optimistic entry.revalidate: Triggers background revalidation to ensure cache consistency.
UI State Feedback
The component maintains a separate React statestateto display messages indicating the current mutation status: optimistic update, success, rollback on error, or revalidation.Rendering
The to-do list renders from the SWR cache, reflecting optimistic updates instantly and syncing with server-confirmed data after revalidation.
Integration
This Basic Optimistic UI subtopic is a practical demonstration of mutation handling within the Remote Data Mutation parent topic but scoped to a minimal setup using only SWR’s core features and React state.
Relation to Core Data Fetching:
It builds uponuseSWRfor fetching and caching data, highlighting howmutatecan be leveraged not just for revalidation but also for optimistic updates.Relation to Remote Data Mutation:
While the parent mutation topic may cover advanced mutation hooks and middleware, this example shows a straightforward pattern without extra abstractions or libraries like Immer.Complementing Immer-based Optimistic UI:
This subtopic offers a simpler alternative to using Immer for immutable updates, useful for developers seeking a lightweight approach or introductory example.User Experience Enhancement:
By combining optimistic UI with background revalidation and rollback mechanisms, it ensures UI responsiveness without sacrificing data correctness.
Diagram
The following flowchart illustrates the optimistic update lifecycle when adding a new to-do item:
flowchart TD
A[User Enters To-Do and Clicks Add] --> B[Trigger mutate with optimisticData]
B --> C[Update Cache Immediately with New Item]
C --> D[Render Updated List with Optimistic Data]
B --> E[Send POST Request to Server]
E --> F{Server Response?}
F -->|Success| G[populateCache with Server-Returned Item]
G --> H[Render Updated List with Server Data]
F -->|Error| I[Rollback Cache to Previous State]
I --> J[Render List with Original Data]
G --> K[Trigger Background Revalidation]
K --> L[Ensure Cache Consistency with Server]
This flow highlights how the UI updates immediately on user action, reconciles with the server response, and handles errors gracefully by rolling back to a consistent state.
This approach enables a seamless, fast user experience while maintaining the integrity of the cached data through SWR’s built-in mutation and revalidation capabilities.