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.
- Generic, type-safe
useOptimistichook - 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.
- Import the hook and provide an initial state:
const { state, update, isPending, error } = useOptimistic({ likes: 0 });- Update state optimistically while performing async operation:
update(
(prev) => ({ likes: prev.likes + 1 }),
async (newState) => {
await fakeApiUpdate(newState.likes);
}
);isPendingindicates whether the async operation is in progress.errorprovides rollback notification if the operation fails.
- Waiting for server confirmation before updating UI
- UI feels sluggish
- Leads to poor user experience and harder-to-maintain code
- 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
src/
hooks/
useOptimistic.ts ← core hook logic
components/
OptimisticDemo.tsx ← demo UI to test hook
OptimisticDemo.css ← styling
App.tsx ← integrates demo component
- 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
npm install
npm run devMIT