valtio-sync-tabs
v0.1.0
Published
Sync your Valtio state across browser tabs
Maintainers
Readme
valtio-sync-tabs
Sync your Valtio state across browser tabs.
npm install valtio-sync-tabsThis library is greatly inspired by pinia-shared-state.
Basic Usage with React Hook
Define the Valtio store to share in your store.js
import { proxy } from 'valtio'
const state = proxy({
$id: 'shared-valtio-state', // Add a unique `$id` field here
count: 0,
})Call useSharedValtioState and then consume the store all the same in your Component.tsx
import { useSnapshot } from 'valtio'
import { useSharedValtioState } from 'valtio-sync-tabs'
function MyComponent() {
// Share the entire state across tabs
useSharedValtioState(state, {
// Get initial state from other tabs
initialize: true,
})
// Everything is the same as valtio then
const snap = useSnapshot(state)
return (
<div>
<p>Count: {snap.count}</p>
<button onClick={() => state.count++}>Increment</button>
</div>
)
}How It Works
- BroadcastChannel is used to communicate between browser tabs
- Conflict resolution is timestamp-based, latest wins
- State should be superjson serializable
License
MIT
