-
Notifications
You must be signed in to change notification settings - Fork 0
useSharedState
A highly advanced global state manager that syncs seamlessly across components AND across multiple browser tabs simultaneously. Uses the native BroadcastChannel API under the hood to ensure real-time state synchronization without needing heavy context providers.
Sharing a piece of state across multiple completely disconnected components in the same application.
import { useSharedState } from "react-hook-lab";
function Header() {
const [theme, setTheme] = useSharedState("global_theme", "light");
return <button onClick={() => setTheme("dark")}>Dark Mode</button>;
}
function Footer() {
// This stays instantly synced with the Header component!
const [theme] = useSharedState("global_theme", "light");
return <p>Current theme: {theme}</p>;
}Syncing state across multiple separate browser tabs in real-time. If you duplicate the tab, they will stay locked together!
import { useSharedState } from "react-hook-lab";
function ShoppingCart() {
const [cartCount, setCartCount] = useSharedState("cart_items", 0);
// If you open this app in Tab A and Tab B, clicking this button in Tab A
// instantly updates the number in Tab B as well!
return (
<button onClick={() => setCartCount(prev => prev + 1)}>
Add to Cart ({cartCount})
</button>
);
}Pausing subscriptions in specific components to optimize renders.
import { useSharedState } from "react-hook-lab";
function DebugPanel({ isPanelOpen }: { isPanelOpen: boolean }) {
// By passing `enabled: false`, this hook immediately stops listening to BroadcastChannel
// updates. It won't trigger re-renders in this component until `enabled` becomes true again,
// making it an incredibly powerful performance optimization.
const [logs, setLogs] = useSharedState("system_logs", [], {
enabled: isPanelOpen
});
if (!isPanelOpen) return null;
return <div>{logs.length} Errors Found</div>;
}-
key- Type:
string - Description: The unique global identifier for this piece of shared state. It is used as the BroadcastChannel name.
- Type:
-
initialValue- Type:
T | (() => T) - Description: The default value. If multiple components define the same key, the first one to mount initializes the master state.
- Type:
-
options(Optional)- Type:
{ enabled?: boolean } - Description: Configuration object. If
enabledis false, the hook pauses all subscriptions and broadcasting.
- Type:
Returns a tuple identical to React's useState:
-
state(T): The globally synchronized value. -
setState((action: T | ((prev: T) => T)) => void): Function to update the global state. This update is instantly broadcasted to all subscribers.
useSharedState leverages React 18's useSyncExternalStore tied to a custom high-performance engine.
When a component mounts, it subscribes to an internal SnapshotManager for that specific key.
When setState is called:
- The new state is calculated and saved in the internal memory store.
- The
SharedEnginefires aBroadcastChannelmessage into the browser ether. - Every component (in the current tab) subscribed to that
keyis immediately notified and forced to re-render. - If there are other browser tabs open on the same origin, their
BroadcastChannellisteners intercept the message and instantly update their own internal memory stores, cascading the re-render across the entire browser session.
Built with ❤️ by Saurav-TB-Pandey. | Report an Issue | NPM