Cross-Tab State Sync: Introducing useIndexedDB for React

Leader 1 2 17
calendar_today agoschedule1 min read
— Originally published at dev.to

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.


Originally published on my blog. You can read the alternative breakdown here.

🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

SolidJS 2.0 Async Data: A Deep Dive for React Devs

morellodev - Jul 16

How I Built a React Portfolio in 7 Days That Landed ₹1.2L in Freelance Work

Dharanidharan - Feb 9

TypeScript Complexity Has Finally Reached the Point of Total Absurdity

Karol Modelski - Apr 23

I’m a Senior Dev and I’ve Forgotten How to Think Without a Prompt

Karol Modelski - Mar 19

Sovereign Intelligence: The Complete 25,000 Word Blueprint (Download)

Pocket Portfolio - Apr 1
chevron_left
1.1k Points20 Badges
16Posts
0Comments
3Connections
An independent and self-motivated engineering enthusiast with an innovative mindset.

Commenters (This Week)

1 comment
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!