LogoRobo.js
Packages@robojs/sync

useSyncState()

Function: useSyncState()

function useSyncState<T, ClientData>(initialState, key): readonly [T, (newState) => void, SyncContext<ClientData>]

Hook for synchronized state across clients.

Works like React's useState, but the state is shared across all clients subscribed to the same key. Updates from any client are broadcast to all others.

Type Parameters

Type ParameterDefault type
T-
ClientDataunknown

Parameters

ParameterType
initialStateT
key(null | string)[]

Returns

readonly [T, (newState) => void, SyncContext<ClientData>]

Examples

// Basic usage (backward compatible)
const [position, setPosition] = useSyncState({ x: 0, y: 0 }, ['player-position'])
// With context (new in v2)
const [gameState, setGameState, context] = useSyncState(initialGameState, ['game-room'])
console.log(context.clients, context.isHost)

On this page