🛍️ Shopping Cart Demo

Showcasing useSharedState - Real-time state sharing without prop drilling!

Re-render: 0

Product Catalog

Cart Items:
0
🎧

Wireless Headphones

$99.99

📱

Smartphone Case

$24.99

🔋

Portable Charger

$39.99

🛍️ Component A: Product catalog that adds items to shared cart state. Watch Component B update instantly when you add items!

Re-render: 0

Shopping Cart

Total: $0.00
🛒

Your cart is empty

Add items from Component A to get started!

🛒 Component B: Shopping cart that shares state with Component A. Add items from the catalog and watch them appear here instantly!

Re-render: 0

👤 User Settings

Persistent (@user-settings)Cross-tab Sync

This component demonstrates persistent user settings that survive page refresh and sync across browser tabs. Try opening this page in another tab to see real-time synchronization!

Name not set

Phone not set

Email not set

💾 Auto-saved to localStorage | 🔄 Syncs across tabs

📚 useSharedState Documentation

🎯 What is useSharedState?

useSharedState is a revolutionary React hook that enables real-time state sharing between components without prop drilling, context providers, or complex state management libraries. Built on top of SWR's caching mechanism, it provides a simple, elegant solution for cross-component state synchronization. Plus, keys prefixed with @ are automatically persisted to localStorage and synchronized across tabs!

✨ Key Features

🚀 Zero Boilerplate

No providers, reducers, or complex setup required.

⚡ Real-time Sync

Changes propagate instantly across all components.

🎯 Selective Sharing

Share only what you need with key-based access.

🔒 Type Safe

Full TypeScript support with generic types.

💾 Auto Persistence

Keys with @ prefix persist to localStorage automatically.

🌐 Cross-tab Sync

Persistent state syncs across browser tabs in real-time.

📖 Basic Usage


const [count, setCount] = useSharedState('counter', 0);


const [count, setCount] = useSharedState('counter');


const [cart, setCart] = useSharedState('@cart-items', []);

📋 API Reference

useSharedState<T>(key: string,initialValue?: T)
Parameters:
  • key - Unique identifier for the shared state. Keys starting with @ are automatically persisted to localStorage and synced across tabs.
  • initialValue - Optional initial value (used only on first access)
Returns:

[value, setValue] - Current value and setter function (just like useState!)

⚙️ How It Works

1

Global State Storage

Uses a Map to store shared state with string keys for efficient access.

2

SWR Integration

Leverages SWR's caching and revalidation system for state synchronization.

3

Automatic Updates

When state changes, SWR's mutate() triggers re-renders across all subscribed components.

🚀 Advanced Examples

Complex State Objects

const [user, setUser] = useSharedState<User>('current-user');

Array State

const [items, setItems] = useSharedState<CartItem[]>('cart-items', []);

Updater Functions

setCount(prev => (prev || 0) + 1);

Persistent State (Cross-tab + Refresh Proof)

const [settings, setSettings] = useSharedState<Settings>('@user-settings');

⚖️ Comparison

FeatureuseSharedStateReduxContext
Setup✅ Zero❌ Complex⚠️ Providers
Performance✅ Optimized✅ Good❌ Re-renders
Learning Curve✅ Minimal❌ Steep⚠️ Moderate

💡 Best Practices

  • • Use descriptive, unique keys for different state types
  • • Provide initial values for better TypeScript inference
  • • Consider using constants for frequently used keys
  • • Use @ prefix for data that should persist across page refreshes
  • • Persistent keys automatically sync across browser tabs
  • • Perfect for forms, shopping carts, user preferences, and UI state
  • • Great for prototyping and small to medium applications