Experimental Hooks
useSuspenseIndexedDBState
About
⚠️ Experimental Hook: This hook may be removed or significantly changed in any release without notice.
A Suspense-enabled hook for IndexedDB state management with cross-tab synchronization. This hook suspends during initialization and must be wrapped in a Suspense boundary. It provides full TypeScript generic support, structured data storage without JSON serialization limits, error handling, and automatic synchronization across browser tabs using BroadcastChannel API.
Examples
Basic usage with simple values
Working with Complex Objects and TypeScript
Custom Database Configuration
Storing Binary Data and Complex Structures
Cross-tab Synchronization
The hook automatically synchronizes state changes across browser tabs using the BroadcastChannel API:
Arguments
Argument | Type | Description | Required |
---|---|---|---|
key | string | The key to use within the IndexedDB object store | Yes |
initializer | (currentValue: unknown) => T | Function that transforms the raw IndexedDB value into typed state | Yes |
config | IndexedDBConfig | Optional configuration object | No |
IndexedDBConfig
Property | Type | Default | Description |
---|---|---|---|
dbName | string | "rooks-db" | The IndexedDB database name |
storeName | string | "state" | The object store name within the DB |
version | number | 1 | The database version |
Return Value
Returns a tuple containing:
currentValue: T
- The current state value of type Tcontrols: object
- An object containing:getItem(): T
- Get the current value from statesetItem(value: T): Promise<void>
- Set a new value (async)deleteItem(): Promise<void>
- Delete the item and reset to initial value (async)
Type Safety
The hook is fully type-safe and supports TypeScript generics:
Error Handling
The hook handles various error scenarios gracefully:
- IndexedDB not supported: Falls back to in-memory state
- Database opening errors: Throws errors that can be caught by error boundaries
- Transaction errors: Logs errors and maintains existing state
- Initializer errors: Throws errors that can be caught by error boundaries
IndexedDB vs localStorage Comparison
Feature | useSuspenseIndexedDBState | useSuspenseLocalStorageState |
---|---|---|
Data Types | Native objects, binary data | JSON serializable only |
Storage Limit | ~1GB+ (browser dependent) | ~5-10MB |
Performance | Better for large data | Better for small data |
Cross-tab Sync | BroadcastChannel API | Storage events |
Browser Support | Modern browsers | All browsers |
Async Operations | Yes (Promises) | No (synchronous) |
Complex Objects | Native support | JSON serialization required |
Browser Support
- IndexedDB: Supported in all modern browsers (IE 10+)
- BroadcastChannel: Supported in modern browsers (Chrome 54+, Firefox 38+, Safari 15.4+)
- Fallback: When BroadcastChannel is not available, cross-tab sync is disabled but the hook still works