use-db-state
v2.1.1
Published
A React Hook that uses IndexedDB in the browser to persistently store and retrieve state.
Downloads
139
Maintainers
Readme
useDbState
🚀 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.
[email protected] can now be used as a global state!
✨ Features
- 🌍 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
🎮 Live Examples
Here are several live examples demonstrating different use cases and features of useDbState
:
Basic Counter with Persistence
View Demo
A simple counter example showing how state persists across page refreshes. Perfect for getting started with useDbState
.
String State Sharing
View Demo Demonstrates how two components can share a string state, showing real-time updates between components.
Optimized Number Updates
View Demo Showcases the hook's handling of rapid state changes with numbers, featuring:
- Race condition prevention
- Internal debouncing
- Optimized performance for fast updates
Array State Management
View Demo Shows how arrays are handled in shared state:
- Adding elements to array
- Real-time updates across components
- Array manipulation with persistence
Object State Handling
View Demo Demonstrates working with complex object states:
- Object property updates
- Nested object handling
- State synchronization between components
Image Storage and Sharing
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.
📦 Installation
npm install use-db-state
# or
yarn add use-db-state
# or
pnpm add use-db-state
🚀 Quick Start
import { useDbState } from 'use-db-state';
function Counter() {
const [count, setCount] = useDbState('counter', 0);
return (
<button onClick={() => setCount(prev => prev + 1)}>
Count: {count}
</button>
);
}
📖 Global State Usage
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.
📚 API Reference
useDbState
function useDbState<T>(
key: string,
defaultValue?: T,
dbName?: string,
storeName?: string,
options?: {
debounceTime?: number;
}
): [T, (value: T | ((prev: T) => T)) => void]
Parameters
key
(required): Unique identifier for the statedefaultValue
: Initial value if none exists in storagedbName
: Database name (default: 'userDatabase')storeName
: Store name (default: 'userData')options
: Configuration objectdebounceTime
: Milliseconds to debounce writes (default: 100)
Returns
Returns a tuple containing:
- Current state value
- Setter function (accepts new value or updater function)
useDbKeyRemover
function useDbKeyRemover(
dbName?: string,
storeName?: string
): (key: string) => Promise<void>
⚡ Performance Considerations
- 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
🤝 Contributing
Contributions are welcome! Please read our Contributing Guide for details on our code of conduct and the process for submitting pull requests.
📄 License
MIT © Ajey Nagarkatti
🔍 Keywords
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