DEV Community

Saurav Pandey
Saurav Pandey

Posted on

Fixing Cross-Tab Real-Time Syncing in React: Patching useIndexedDB

If you use browser storage across multiple tabs, keeping state in sync can be tricky. In react-hook-lab, we recently resolved a cross-tab synchronization bug in the useIndexedDB hook.

The Issue

Previously, useIndexedDB created its underlying BroadcastChannel lazily during the first write operation. While this worked great for tabs actively saving data, tabs that only read data never initialized the channel on mount. As a result, read-only tabs remained out of sync when updates occurred in sibling tabs.

The Solution

The hook now opens the cross-tab channel on mount whenever enabled. Even if a tab never triggers a write operation, it immediately listens for external state changes.

Code Example 1: Read-Only Monitor Tab

Here is how a tab that only reads data automatically stays up to date:

import React from 'react';
import { useIndexedDB } from 'react-hook-lab';

export function UserStatusViewer() {
  // Read-only subscription to IndexedDB state
  const { value: status, status: dbStatus } = useIndexedDB<string>('user-session', {
    defaultValue: 'Offline',
  });

  if (dbStatus === 'loading') return <p>Loading status...</p>;

  return (
    <div>
      <h3>Current User Status</h3>
      <p>{status}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Code Example 2: Writer Tab Updating Shared State

When another tab performs a write, the read-only tab above updates instantly:

import React from 'react';
import { useIndexedDB } from 'react-hook-lab';

export function UserStatusEditor() {
  const { value: status, setValue } = useIndexedDB<string>('user-session', {
    defaultValue: 'Offline',
  });

  return (
    <div>
      <button onClick={() => setValue('Online')}>Set Online</button>
      <button onClick={() => setValue('Away')}>Set Away</button>
      <p>Active Status: {status}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Resources


Buy Me A Coffee

Enjoyed this breakdown? Support my open-source work on Buy Me a Coffee or explore react-hook-lab!

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

Top comments (0)