Managing persistent application state often involves a trade-off between the simplicity of localStorage and the performance of IndexedDB. Today, I’m excited to announce the addition of useIndexedDB to react-hook-lab.
Why useIndexedDB?
IndexedDB is powerful, but its asynchronous, event-driven API is notoriously difficult to integrate into React’s declarative lifecycle. useIndexedDB abstracts this complexity, offering a useState-like experience that automatically handles cross-tab synchronization.
Getting Started
First, configure your database once at the root of your application:
import { createIndexedDB } from 'react-hook-lab';
createIndexedDB({
dbName: 'my-app-db',
stores: ['settings']
});
Now, you can consume your state anywhere in your component tree:
import { useIndexedDB } from 'react-hook-lab';
function ThemeToggle() {
const [theme, setTheme, meta] = useIndexedDB('settings', 'ui-theme', 'light');
if (meta.status === 'loading') return <div>Loading...</div>;
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Current theme: {theme}
</button>
);
}
Key Features
-
Cross-Tab Synchronization: Updates made in one tab are instantly reflected in others via
BroadcastChannel. - Optimistic Updates: Your UI stays responsive by updating locally before the asynchronous database write finishes.
- Simplified API: No more manual transaction management or event listener boilerplate.
Resources
Originally published on my blog. You can read the alternative breakdown here.
Top comments (0)