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 Parameter | Default type |
|---|---|
T | - |
ClientData | unknown |
Parameters
| Parameter | Type |
|---|---|
initialState | T |
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)