Optimistic UI Examples
This module demonstrates practical example applications that implement optimistic UI updates using the SWR library's mutation capabilities. It includes two key patterns:
Basic Optimistic UI: Direct optimistic updates with rollback support.
Immer-based Optimistic UI: Leveraging the Immer library for immutable state updates in optimistic mutations.
These examples showcase how to immediately reflect user actions in the UI while asynchronously syncing with the server, enhancing responsiveness and user experience.
Core Concepts and Purpose
What is Optimistic UI?
Optimistic UI is a technique where the application immediately updates the user interface to reflect a user's action before the server confirms the change. This approach reduces perceived latency and creates a smoother interaction.
Why This Module Exists
When performing remote mutations (e.g., adding items), waiting for server confirmation before updating the UI leads to sluggish user experiences. This module provides example implementations of how SWR's mutation API supports optimistic updates while:
Maintaining data consistency by rolling back on error.
Supporting cache synchronization after server response.
Allowing immutable state management for complex state shapes (via Immer).
How the Module Works
Basic Optimistic UI Example (examples/optimistic-ui/pages/index.js)
This example shows a todo list where new items are:
Immediately appended to the UI list optimistically.
Sent asynchronously to the server via a POST request.
The local cache is updated with the server response.
If the request fails, SWR rolls back to the previous state automatically.
Key workflow:
User enters text and clicks "Add".
mutateis called with:optimisticData: local optimistic update of the list.rollbackOnError: enables rollback if mutation fails.populateCache: a function to update cache with the server response.revalidate: triggers background revalidation.
await mutate(
fetch('/api/todos', {
method: 'POST',
body: JSON.stringify(newTodo)
}),
{
optimisticData: [...data, newTodo],
rollbackOnError: true,
populateCache: newItem => [...data, newItem],
revalidate: true
}
)
The UI state (state) is also managed to provide feedback messages during mutation and revalidation.
Immer-based Optimistic UI Example (examples/optimistic-ui-immer/pages/index.js)
This example demonstrates using Immer with SWR's mutate for immutable optimistic updates on an array of strings.
Key workflow:
When submitting new text:
mutateis called with an Immerproducefunction that mutates a draft copy of the cached data immutably.The local cache is updated immediately without revalidation (
false).Then a POST request is sent to the server.
On server response,
mutateupdates the cache with fresh data from the response.
mutate("/api/data", produce(draftData => {
draftData.push(text)
}), false)
mutate('/api/data', await fetch('/api/data', {
method: 'POST',
body: JSON.stringify({ text })
}))
This pattern allows writing mutable update logic while maintaining immutability under the hood, simplifying complex state updates.
Interaction with Other Parts of the System
SWR Core Hooks: Both examples use
useSWRfor data fetching and cache management.Mutation API: The
mutatefunction from SWR is central to updating the cache both optimistically and after server responses.Fetch Utility: A shared
fetchhelper abstracts the network request, used by both examples to communicate with API endpoints.API Routes: The server-side endpoints (
/api/dataand/api/todos) handle GET and POST requests, returning updated resource lists or new items. They simulate asynchronous mutation responses and validate data.
This module depends on the core SWR mutation mechanisms and cache management to synchronize UI state with remote data, providing seamless real-time feedback.
Important Concepts and Design Patterns
Optimistic Mutation with Rollback
Optimistic update: Immediately update local cache to reflect intended changes.
Rollback on error: If the mutation fails, automatically revert cache to previous state.
Revalidation: Optionally refetch data after mutation to ensure consistency.
Immutable State Management with Immer
Immer enables writing "mutable" logic that produces an immutable next state.
This approach simplifies complex state transformations in optimistic updates.
Used here to push new items immutably into the cached array.
Feedback UI States
The basic optimistic UI example manages UI feedback states (
info,success,error) to inform users about mutation progress and results.This pattern can be extended for better user experience in mutation-heavy interfaces.
Mermaid Flowchart: Optimistic UI Mutation Workflow
flowchart TD
A[User Inputs New Item] --> B[Trigger mutate with Optimistic Data]
B --> C[Update Local Cache Immediately]
C --> D[Send POST Request to Server]
D -->|Success| E[Update Cache with Server Response]
D -->|Error| F[Rollback Cache to Previous State]
E --> G[Trigger Revalidation (optional)]
F --> G
G --> H[UI Reflects Latest Consistent Data]
This flowchart summarizes the optimistic UI mutation lifecycle, illustrating immediate UI update, asynchronous server sync, error rollback, and optional revalidation.
Summary of Key File Interactions
File Path | Role |
|---|---|
Basic optimistic UI example with rollback and feedback state | |
| Immer-based optimistic UI example with immutable updates |
Shared fetch helper for API calls | |
API Routes ( | Server endpoints handling GET and POST requests |
These files work together to demonstrate how optimistic UI patterns are implemented and integrated with SWR's mutation and caching system.
This documentation page provides a detailed explanation of the Optimistic UI Examples topic, focusing on how the module uses SWR's mutation capabilities and Immer to implement responsive, consistent UI updates during asynchronous data mutations.