🚀 A powerful React hook for persistent state management with IndexedDB, featuring global state management, automatic caching, and optimized performance.
useDbState
is a production-ready React hook that combines the simplicity of useState
with the persistence of IndexedDB and power of global state management. It's perfect for managing application-wide state, offline-first applications, and sharing state between components.
- 🌍 Global State Management: Share state seamlessly between components
- 💾 Persistent Storage: Data persists through page reloads and browser restarts
- ⚡ Performance Optimized:
- In-memory caching for fast reads
- Debounced writes to reduce database operations
- Queued operations to prevent race conditions
- 🛡️ Reliable: Automatic error handling and recovery
- 🔍 Developer Friendly: Comprehensive debugging support
- 📱 Universal: Works in all modern browsers and React Native
Here are several live examples demonstrating different use cases and features of useDbState
:
View Demo
A simple counter example showing how state persists across page refreshes. Perfect for getting started with useDbState
.
View Demo Demonstrates how two components can share a string state, showing real-time updates between components.
View Demo Showcases the hook's handling of rapid state changes with numbers, featuring:
- Race condition prevention
- Internal debouncing
- Optimized performance for fast updates
View Demo Shows how arrays are handled in shared state:
- Adding elements to array
- Real-time updates across components
- Array manipulation with persistence
View Demo Demonstrates working with complex object states:
- Object property updates
- Nested object handling
- State synchronization between components
View Demo Advanced example showing:
- Binary data storage
- Image handling in IndexedDB
- Sharing images between components
- Efficient large data management
Each example is fully interactive and can be edited live on StackBlitz. They serve as both documentation and a playground for learning how to use useDbState
effectively.
npm install use-db-state
# or
yarn add use-db-state
# or
pnpm add use-db-state
import { useDbState } from 'use-db-state';
function Counter() {
const [count, setCount] = useDbState('counter', 0);
return (
<button onClick={() => setCount(prev => prev + 1)}>
Count: {count}
</button>
);
}
import { useDbState, useDbKeyRemover } from 'use-db-state';
function ComponentOne() {
const [myValue, setMyValue] = useDbState('myValue', '');
const removeMyKey = useDbKeyRemover();
const handleChange = (e) => {
setMyValue(e.target.value);
};
return (
<div className="App">
<h1>My App</h1>
<div>
<input type='text' value={myValue} onChange={handleChange} />
<button onClick={() => removeMyKey('myValue')}>Remove myValue</button>
</div>
</div>
);
}
function ComponentTwo() {
const [myValue, setMyValue] = useDbState('myValue'); // You now have access to the myValue state from ComponentOne
return (
<div className="App">
<h1>My App</h1>
<div>
<p>myValue: {myValue}</p>
</div>
</div>
);
}
In this example, useDbState
is used to create a global state variable myValue
that can be accessed and modified from any component. The state is persisted in IndexedDB, so it will be preserved across page reloads. The useDbKeyRemover hook is used to remove the key myValue
from the IndexedDB object store when needed.
function useDbState<T>(
key: string,
defaultValue?: T,
dbName?: string,
storeName?: string,
options?: {
debounceTime?: number;
}
): [T, (value: T | ((prev: T) => T)) => void]
-
key
(required): Unique identifier for the state -
defaultValue
: Initial value if none exists in storage -
dbName
: Database name (default: 'userDatabase') -
storeName
: Store name (default: 'userData') -
options
: Configuration object-
debounceTime
: Milliseconds to debounce writes (default: 100)
-
Returns a tuple containing:
- Current state value
- Setter function (accepts new value or updater function)
function useDbKeyRemover(
dbName?: string,
storeName?: string
): (key: string) => Promise<void>
- In-Memory Cache: First reads are cached for instant access
- Debounced Writes: Prevents excessive database operations
- Operation Queue: Ensures write operations are atomic
- Cleanup: Automatic subscription cleanup on unmount
Contributions are welcome! Please read our Contributing Guide for details on our code of conduct and the process for submitting pull requests.
MIT © Ajey Nagarkatti
react, hook, indexeddb, state management, persistent storage, cross-tab synchronization, react-hooks, browser storage, offline-first, web storage, react state, database, web development, frontend, javascript
Made with ❤️ for the React community