Skip to content

vkmalik/optimistic-ui-updates

Repository files navigation

Optimistic UI Updates (React + TypeScript)

A reusable, type-safe hook and demo for implementing optimistic UI updates in React applications. This pattern improves perceived performance by updating the UI immediately while async operations are in progress, and handles failures gracefully.


What This Repo Shows

  • Generic, type-safe useOptimistic hook
  • Immediate UI update (optimistic update)
  • Async operation in the background
  • Rollback on failure
  • Loading and error state handling
  • Decoupled state management from UI logic
  • Minimal demo component for visualization

This pattern is suitable for forms, counters, likes, or any user action where instant feedback is critical.


How It Works

  1. Import the hook and provide an initial state:
const { state, update, isPending, error } = useOptimistic({ likes: 0 });
  1. Update state optimistically while performing async operation:
update(
  (prev) => ({ likes: prev.likes + 1 }),
  async (newState) => {
    await fakeApiUpdate(newState.likes);
  }
);
  1. isPending indicates whether the async operation is in progress.
  2. error provides rollback notification if the operation fails.

Bad Pattern

  • Waiting for server confirmation before updating UI
  • UI feels sluggish
  • Leads to poor user experience and harder-to-maintain code

Good Pattern (This Repo)

  • Immediate feedback for the user
  • Async call handled in the background
  • Automatic rollback on failure
  • Clean, reusable, type-safe hook
  • Minimal dependency on external libraries

Project Structure

src/
  hooks/
    useOptimistic.ts       ← core hook logic
  components/
    OptimisticDemo.tsx     ← demo UI to test hook
    OptimisticDemo.css     ← styling
  App.tsx                  ← integrates demo component

Demo

  • Click "Like" button to increment counter
  • UI updates immediately while async operation is in progress
  • Rollback occurs on simulated failure (randomized 20% failure chance)
  • Loading and error states handled

Installation

npm install
npm run dev

Open http://localhost:5173


License

MIT

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published