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:

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:


How the Module Works

Basic Optimistic UI Example (examples/optimistic-ui/pages/index.js)

This example shows a todo list where new items are:

Key workflow:

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:

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

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

Immutable State Management with Immer

Feedback UI States


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

examples/optimistic-ui/pages/index.js

Basic optimistic UI example with rollback and feedback state

examples/optimistic-ui-immer/pages/index.js

Immer-based optimistic UI example with immutable updates

examples/optimistic-ui/libs/fetch.js

Shared fetch helper for API calls

API Routes (/api/data, /api/todos)

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.