When building rich web applications that rely on IndexedDB, users frequently work across multiple browser tabs. A common requirement is ensuring that changing data in one tab reflects instantly across all open tabs.
The Multi-Tab Challenge
In previous versions of react-hook-lab, the useIndexedDB hook delayed opening its cross-tab communication channel until the first write occurred. While efficient for writing components, components that only read state were left unaware of updates happening in companion tabs.
The Fix
We updated useIndexedDB to establish the cross-tab broadcast channel immediately when the component mounts. Now, every subscriber tab stays synchronized regardless of whether it writes data.
Example 1: Displaying Synchronized State
A secondary dashboard tab listening to shared IndexedDB updates:
import React from 'react';
import { useIndexedDB } from 'react-hook-lab';
export function NotificationBadge() {
const { value: count } = useIndexedDB<number>('unread-count', {
defaultValue: 0,
});
return <span className="badge">Unread: {count}</span>;
}Example 2: Triggering State Changes across Tabs
A primary control panel writing to IndexedDB:
import React from 'react';
import { useIndexedDB } from 'react-hook-lab';
export function NotificationController() {
const { value: count, setValue } = useIndexedDB<number>('unread-count', {
defaultValue: 0,
});
return (
<button onClick={() => setValue(count + 1)}>
Add Notification ({count})
</button>
);
}Resources
Enjoyed this engineering guide?
Support independent software development and open-source research.
Comments
Post a Comment