Multi-Tab State Sync Made Easy: Introducing useSharedState in react-hook-lab!

Multi-Tab State Sync Made Easy: Introducing useSharedState in react-hook-lab!

If you've ever had to build a web application where users open multiple tabs, you know the struggle of keeping state synchronized. Whether it's a shopping cart, user preferences, or live dashboard configurations, manual synchronization using localStorage events or WebSockets can quickly turn into a boilerplate-heavy headache.

Today, I'm thrilled to share a major feature update to react-hook-lab: the introduction of the useSharedState hook! This release also includes some source-tree spring cleaning to ensure a lighter, cleaner library.

What's New: Multi-Tab State Synchronization ๐Ÿ”„

The star of this release is the new useSharedState hook. This hook allows you to seamlessly share and synchronize state across multiple browser tabs or windows in real-time, completely out of the box.

Under the hood, useSharedState is powered by a robust, custom-engineered sync engine:

  • BroadcastChannel Transport: It utilizes the native BroadcastChannel API to instantly broadcast state updates across same-origin tabs.
  • Conflict Resolution: If two tabs update state at almost the same time, the engine automatically resolves conflicts using logical versioning and unique tab identifiers.
  • Reactive Event Bus: An internal event bus coordinates local state changes with React's rendering lifecycle.
  • Snapshot Management: It integrates smoothly with modern React state mechanics, ensuring zero tearing and optimal re-rendering.

How to Use It

Using useSharedState is designed to feel exactly like using React's native useState. Just provide a unique sync key and an initial value:

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

function ThemeSelector() {
  // State is automatically synchronized across all open tabs!
  const [theme, setTheme] = useSharedState('app-theme', 'light');

  return (
    <div>
      <p>Current Theme: {theme}</p>
      <button onClick={() => setTheme('light')}>Light Mode</button>
      <button onClick={() => setTheme('dark')}>Dark Mode</button>
    </div>
  );
}

Library Housekeeping ๐Ÿงน

As part of our commitment to keeping the repository clean and maintainable, we have also done some housekeeping. We removed pre-compiled build files (index.js and index.d.ts) from the root of the source tree. This ensures that our version control remains focused strictly on the TypeScript source code, preventing build artifacts from cluttering up pull requests.


Resources & Links

Comments