LogoRobo.js

useSyncContext

Track connected clients and host status for a sync key.

Access room context without managing state. Track connected clients, determine host status, and react to join/leave events.

Signature

// Key only
const context = useSyncContext<ClientData>(key)

// With event callbacks
useSyncContext<ClientData>(options, key)
// Key only
const context = useSyncContext(key)

// With event callbacks
useSyncContext(options, key)

Parameters

Two call signatures. The first argument is either a key array or an options object.

SyncContextOptions:

FieldTypeDescription
onConnect(client: Client<ClientData>) => voidCalled when a client joins
onDisconnect(client: Client<ClientData>) => voidCalled when a client leaves

Return value

Returns a SyncContext object.

FieldTypeDescription
clientsClient<ClientData>[]All connected clients for this key
clientIdstringYour client ID
isHostbooleanWhether you're the room host
broadcast(payload: unknown) => voidSend ephemeral message to all
send(clientId: string, payload: unknown) => voidSend to specific client

Basic usage

import { useSyncContext } from '@robojs/sync'

function PlayerList() {
	const { clients, clientId, isHost } = useSyncContext(['game', roomId])

	return (
		<div>
			<p>{isHost ? 'You are the host' : 'Guest'}</p>
			<ul>
				{clients.map((client) => (
					<li key={client.id}>
						{client.data?.name ?? client.id.slice(0, 6)}
						{client.id === clientId && ' (you)'}
					</li>
				))}
			</ul>
		</div>
	)
}
import { useSyncContext } from '@robojs/sync'

function PlayerList() {
	const { clients, clientId, isHost } = useSyncContext(['game', roomId])

	return (
		<div>
			<p>{isHost ? 'You are the host' : 'Guest'}</p>
			<ul>
				{clients.map((client) => (
					<li key={client.id}>
						{client.data?.name ?? client.id.slice(0, 6)}
						{client.id === clientId && ' (you)'}
					</li>
				))}
			</ul>
		</div>
	)
}

Event callbacks

useSyncContext(
	{
		onConnect: (client) => console.log(`${client.data?.name} joined`),
		onDisconnect: (client) => console.log(`${client.data?.name} left`)
	},
	['game', roomId]
)
useSyncContext(
	{
		onConnect: (client) => console.log(`${client.data?.name} joined`),
		onDisconnect: (client) => console.log(`${client.data?.name} left`)
	},
	['game', roomId]
)

These are useful for notifications, sound effects, or updating UI when players join or leave.

Host determination

The first client to subscribe to a key becomes the host. If the host disconnects, the next client takes over (server-managed). For explicit host control, use SyncZone with hostRules="explicit".

Messaging

The broadcast and send functions from the context send ephemeral messages — they don't persist and aren't state. For persistent ephemeral messaging patterns, see useSyncBroadcast.

Next Steps

On this page