Skip to main content

useOptimistic

The useOptimistic hook provides a wrapper around React’s useOptimistic hook with built-in support for common CRUD operations (add, update, delete) on arrays of data. It’s perfect for implementing optimistic UI updates before server confirmation.

Installation

Import

Usage

Parameters

TData[]
required
An array of data items. Each item must have an id property of type string.

Returns

The hook returns a tuple:
TData[]
The optimistic data array that reflects both the actual data and any pending optimistic updates.
(update: OptimisticUpdate<TData>) => void
A function to trigger optimistic updates. Accepts an object with action (“add” | “update” | “delete”) and item (the data item).

Type Definition

Examples

Todo List with CRUD Operations

Shopping Cart

Comment System

File Upload Manager

Common Patterns

Error Handling with Rollback

Batch Updates

Notes

  • All data items must have an id property of type string
  • The hook uses React’s experimental useOptimistic hook under the hood
  • Optimistic updates are immediately reflected in the UI
  • The actual data prop should be updated when the server confirms the operation
  • The hook automatically handles add, update, and delete operations
  • For updates, items are matched by their id property
  • This hook requires React 18 or later with experimental features enabled
  • Consider implementing error handling and rollback strategies for failed operations