Skip to content

useSharedState

Saurav-TB-Pandey edited this page Aug 10, 2026 · 2 revisions

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.

Usage Examples

Basic

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>;
}

Common

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>
  );
}

Advanced

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>;
}

API Reference

Parameters

  • key
    • Type: string
    • Description: The unique global identifier for this piece of shared state. It is used as the BroadcastChannel name.
  • initialValue
    • Type: T | (() => T)
    • Description: The default value. If multiple components define the same key, the first one to mount initializes the master state.
  • options (Optional)
    • Type: { enabled?: boolean }
    • Description: Configuration object. If enabled is false, the hook pauses all subscriptions and broadcasting.

Return Array

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.

Core Working

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:

  1. The new state is calculated and saved in the internal memory store.
  2. The SharedEngine fires a BroadcastChannel message into the browser ether.
  3. Every component (in the current tab) subscribed to that key is immediately notified and forced to re-render.
  4. If there are other browser tabs open on the same origin, their BroadcastChannel listeners intercept the message and instantly update their own internal memory stores, cascading the re-render across the entire browser session.

Clone this wiki locally