Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/cloudflare/partykit/llms.txt

Use this file to discover all available pages before exploring further.

The PartyServer ecosystem ships first-class React hooks across several packages. Each hook manages socket lifecycle (creation, reconnection, and cleanup) inside useEffect, so your components stay declarative. All hooks require React 18+ and are ESM-only.

usePartySocketpartysocket/react

usePartySocket is the primary hook for connecting a React component to a PartyServer room. It wraps PartySocket and keeps the underlying socket stable across renders: the socket is only recreated when connection-identity options (host, room, party, path, protocol) change — not on every render.
npm install partysocket
import { usePartySocket } from "partysocket/react";

function ChatRoom() {
  const socket = usePartySocket({
    host: "localhost:1999",  // optional, defaults to window.location.host
    room: "general",
    party: "chat",           // optional, defaults to "main"

    onOpen:    (e) => console.log("connected"),
    onMessage: (e) => console.log("message", e.data),
    onClose:   (e) => console.log("disconnected"),
    onError:   (e) => console.error("error", e),
  });

  return (
    <button onClick={() => socket.send("hello!")}>Send</button>
  );
}

Options

OptionTypeDescription
hoststringServer host. Defaults to window.location.host.
roomstringThe room (Durable Object name) to connect to.
partystringThe party namespace. Defaults to "main".
idstringClient connection ID. A random UUID is generated if omitted.
pathstringAdditional path appended to the WebSocket URL.
queryParams | () => Params | Promise<Params>Query parameters. Functions are re-evaluated on each reconnect.
protocol"ws" | "wss"Force a specific WebSocket protocol.
protocolsProtocolsProviderSub-protocols passed to the WebSocket constructor.
basePathstringBase path prefix for the party URL.
prefixstringAlternative URL prefix.
enabledbooleanSet to false to skip connecting. Defaults to true.
onOpen(event) => voidFired when the connection opens.
onMessage(event) => voidFired on each incoming message.
onClose(event) => voidFired when the connection closes.
onError(event) => voidFired on connection error.
transferEnqueuedMessagesboolean | undefinedControls whether messages buffered while disconnected are transferred to a new socket when options change.

Stable socket behavior

usePartySocket serializes connection-identity options into a memo key. The socket is only replaced (and onOpen re-fired) when one of these values changes: host, room, party, path, protocol, protocols, basePath, prefix, id, or query. Event handlers (onMessage, onOpen, etc.) are attached via a ref so you can update them without triggering a reconnect.
function App() {
  const [token, setToken] = useState("");

  const socket = usePartySocket({
    room: "lobby",
    // Changing `query` refreshes credentials without recreating the socket
    query: { token },
    onMessage: (e) => console.log(e.data),
  });
}

enabled flag

Set enabled: false to defer the connection until some condition is met (e.g. the user is authenticated):
const socket = usePartySocket({
  room: "secure-room",
  enabled: isAuthenticated,
});

useWebSocketpartysocket/use-ws

useWebSocket is a lower-level hook that wraps the reconnecting WebSocket class from partysocket without the PartyServer URL conventions. Use it when you need a resilient WebSocket to an arbitrary URL.
import useWebSocket from "partysocket/use-ws";

function RawSocket() {
  const socket = useWebSocket("wss://echo.websocket.org", [], {
    onMessage: (e) => console.log("echo:", e.data),
  });

  return <button onClick={() => socket.send("ping")}>Ping</button>;
}
The hook accepts the same url and protocols arguments as the WebSocket constructor, plus all the reconnecting-websocket Options and event handlers from EventHandlerOptions.

useYProvidery-partyserver/react

useYProvider creates and manages a YProvider instance for Yjs collaborative editing. It handles provider creation and cleanup automatically.
npm install y-partyserver yjs
import useYProvider from "y-partyserver/react";
import * as Y from "yjs";

const yDoc = new Y.Doc();

function Editor() {
  const provider = useYProvider({
    host: "localhost:8787",  // optional, defaults to window.location.host
    room: "my-document",
    party: "my-party",       // optional, defaults to "main"
    doc: yDoc,               // optional — a new Y.Doc is created if omitted
    options: {
      connect: true,
      resyncInterval: -1,
      disableBc: false,
    }
  });

  // use provider.awareness, provider.doc, etc.
}
See the Yjs integration guide for the full list of options, persistence hooks, and custom messaging.

useSyncpartysync/react

useSync is an experimental hook from partysync that synchronizes typed record arrays between a SyncServer Durable Object and a React component. It returns a tuple of [records, dispatch] — similar to useReducer — with optimistic updates applied immediately on the client.
npm install partysync
import { usePartySocket } from "partysocket/react";
import { useSync } from "partysync/react";
import type { TodoRecord, TodoAction } from "./shared";

function TodoApp() {
  const socket = usePartySocket({ room: "my-todos" });

  const [todos, dispatch] = useSync<TodoRecord, TodoAction>(
    "todos",  // channel key — must match the server's channel
    socket,
    // optional optimistic reducer
    (currentState, action) => {
      if (action.type === "create") {
        return [...currentState, [action.payload.id, action.payload.text, 0, Date.now(), Date.now(), null]];
      }
      return currentState;
    }
  );

  return (
    <ul>
      {todos.map(([id, text]) => <li key={id}>{text}</li>)}
    </ul>
  );
}
partysync is experimental and its API is subject to change. It is best suited for syncing small record sets from a single Durable Object per user.

Observable hooks — partytracks/react

partytracks is a WebRTC/audio/video library for Cloudflare Realtime SFU. Its React helpers expose three low-level Observable utility hooks that bridge RxJS Observables into React state.
npm install partytracks rxjs

useObservableAsValue

Subscribes to an Observable and returns its latest emitted value as React state. Unsubscribes automatically on unmount.
import { useObservableAsValue } from "partytracks/react";

function MicStatus({ mic }) {
  // mic.isBroadcasting$ is an Observable<boolean>
  const isBroadcasting = useObservableAsValue(mic.isBroadcasting$, false);

  return <span>{isBroadcasting ? "🔴 Live" : "⏸ Muted"}</span>;
}
Pass a default value as the second argument to avoid an initial undefined.

useObservable

Subscribes to an Observable with a full observer. Useful when you need error or complete callbacks, or want to call setState yourself.
import { useObservable } from "partytracks/react";

function DeviceList({ mic }) {
  const [devices, setDevices] = useState([]);
  useObservable(mic.devices$, { next: setDevices });

  return <select>{devices.map(d => <option key={d.deviceId}>{d.label}</option>)}</select>;
}

useValueAsObservable

Converts a React value into a stable Observable that emits whenever the value changes, and completes on unmount. Use this to feed React state into Observable-based APIs.
import { useValueAsObservable } from "partytracks/react";

function VideoTrack({ preferredDeviceId }) {
  // turns the prop into an Observable<string> for partytracks internals
  const deviceId$ = useValueAsObservable(preferredDeviceId);
}
Pass memoized Observables into useObservableAsValue and useObservable to avoid re-subscribing on every render. Create Observables outside the component or wrap them in useMemo.

Build docs developers (and LLMs) love