Quick start
Build a synced counter app in minutes.
Get a multiplayer counter running from scratch. This guide covers installation, provider setup, and your first useSyncState hook.
Prerequisites
This guide assumes you have an existing Robo project. If not, create one first with npx create-robo my-project.
Setup
Install the plugin
npx robo add @robojs/sync@nextAlso install @robojs/server if you haven't:
npx robo add @robojs/server@nextWrap your app
Add SyncContextProvider at the top of your component tree. Pass clientData to attach metadata visible to other clients.
import { SyncContextProvider } from '@robojs/sync'
export function App() {
return (
<SyncContextProvider clientData={{ name: 'Player1' }}>
<Counter />
</SyncContextProvider>
)
}import { SyncContextProvider } from '@robojs/sync'
export function App() {
return (
<SyncContextProvider clientData={{ name: 'Player1' }}>
<Counter />
</SyncContextProvider>
)
}Create a synced component
Use useSyncState to share state across all connected clients. The third return value provides context about connected clients and host status.
import { useSyncState } from '@robojs/sync'
export function Counter() {
const [count, setCount, context] = useSyncState(0, ['counter'])
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
<p>Players: {context.clients.length}</p>
<p>{context.isHost ? 'You are the host' : 'Guest'}</p>
</div>
)
}import { useSyncState } from '@robojs/sync'
export function Counter() {
const [count, setCount, context] = useSyncState(0, ['counter'])
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
<p>Players: {context.clients.length}</p>
<p>{context.isHost ? 'You are the host' : 'Guest'}</p>
</div>
)
}Run your project
npx robo devOpen multiple browser tabs to see the counter sync in real-time. The first tab becomes the host.
How it works
useSyncStatetakes an initial value and a key array.- Components sharing the same key see the same state.
- The third return value provides context: connected clients, host status, and messaging functions.
- State syncs automatically via WebSocket. No manual handling needed.
