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 partysocket/react module provides React hooks that manage the full lifecycle of a PartySocket or WebSocket connection — creating the socket on mount, reconnecting when connection options change, and cleaning up on unmount. Event handlers (onMessage, onOpen, etc.) are attached in a React-friendly way so you can safely reference state and props from inside them without stale-closure issues.

usePartySocket

import { usePartySocket } from "partysocket/react";
// or default import:
import usePartySocket from "partysocket/react";

Signature

function usePartySocket(options: UsePartySocketOptions): PartySocket
Returns the managed PartySocket instance. The socket is stable across re-renders when connection options are unchanged — you can safely store it in state or pass it to child components.

Options

UsePartySocketOptions combines PartySocketOptions (minus the required host, which becomes optional here) with event handler callbacks and two lifecycle controls:

Connection destination

host
string
Base URL for the party server. When omitted inside a browser, defaults to window.location.host so the socket connects to the current page origin.
room
string
Room name to connect to.
party
string
Party binding name. Defaults to "main".
id
string
Client connection ID. A UUID v4 is generated automatically when omitted.
path
string
Additional path segment appended after the room.
basePath
string
Overrides the entire parties/<party>/<room> path prefix.
prefix
string
Overrides only the parties segment of the default path.
protocol
"ws" | "wss"
Explicit WebSocket protocol override.
protocols
ProtocolsProvider
WebSocket sub-protocol(s) or a (possibly async) function that returns them.
query
Params | (() => Params | Promise<Params>)
Query parameters to include in the URL. Pass a function for dynamic or async values such as auth tokens.
disableNameValidation
boolean
Suppress warnings when party or room contain a forward slash.

Lifecycle controls

enabled
boolean
When false, the socket is closed and held open until enabled becomes true again. Toggling enabled does not create a new socket instance — it calls close() / reconnect() on the existing one. Default: true.
transferEnqueuedMessages
boolean
Controls what happens to messages buffered by send() when the hook must replace the socket because connection options changed:
  • undefined (default) — transfer messages only when the destination is unchanged (i.e. only credential-style options like query changed). If the room, party, host, or path changed, buffered messages are discarded with a warning.
  • true — always transfer buffered messages to the new socket.
  • false — always discard buffered messages, with a warning.

Reconnection options

All standard ReconnectingWebSocket options are also accepted: maxReconnectionDelay, minReconnectionDelay, reconnectionDelayGrowFactor, minUptime, connectionTimeout, maxRetries, maxEnqueuedMessages, startClosed, shouldReconnectOnClose, debug, debugLogger, WebSocket. Changing any reconnection option causes the hook to create a new socket with the updated configuration.

Event handlers

onOpen
(event: Event) => void
Called when the connection opens. The latest callback is always used — no need to unsubscribe and re-subscribe when it changes.
onMessage
(event: MessageEvent) => void
Called when a message is received from the server.
onClose
(event: CloseEvent) => void
Called when the connection closes (whether cleanly or not).
onError
(event: Event) => void
Called when a connection error occurs.

Reconnect behaviour

The socket is replaced (a new PartySocket instance is created) when any of the following change:
  • host, room, party, path, basePath, prefix, protocol, protocols, query, id
  • Any reconnection option (maxRetries, connectionTimeout, etc.)
The socket is not replaced when only the onMessage / onOpen / onClose / onError callback references change — handlers are always updated in place. Similarly, toggling enabled reuses the existing socket.
If query is passed as a function, changing the function’s identity (e.g. a new inline arrow function each render) will cause a reconnect. Wrap the function with useCallback or define it outside the component to stabilise its reference.

useWebSocket

import { useWebSocket } from "partysocket/react";

Signature

function useWebSocket(
  url: UrlProvider,
  protocols?: ProtocolsProvider,
  options?: UseWebSocketOptions
): WebSocket
A lower-level hook that wraps the WebSocket class (i.e. ReconnectingWebSocket) directly, without the PartyKit room URL-building logic. Use this when you want React lifecycle management for an arbitrary WebSocket endpoint.
url
UrlProvider
required
The endpoint to connect to: a string, () => string, or () => Promise<string>. Changing the URL causes the hook to replace the socket.
protocols
ProtocolsProvider
Sub-protocol(s) or a provider function. Changing this also triggers a socket replacement.
options
UseWebSocketOptions
Accepts all Options from ReconnectingWebSocket plus enabled, transferEnqueuedMessages, and the same onOpen, onMessage, onClose, onError event handlers as usePartySocket.
Returns the managed WebSocket instance.

Usage examples

Chat room component

import { usePartySocket } from "partysocket/react";

function Chat() {
  const socket = usePartySocket({
    host: "my-worker.workers.dev",
    room: "general",
    party: "chat",
    onMessage(event) {
      console.log("received:", event.data);
    },
  });

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

Sending and receiving messages with state

import { useState } from "react";
import { usePartySocket } from "partysocket/react";

function Chat() {
  const [messages, setMessages] = useState<string[]>([]);

  const socket = usePartySocket({
    host: "my-worker.workers.dev",
    room: "lobby",
    onMessage(event) {
      setMessages((prev) => [...prev, event.data]);
    },
    onOpen() {
      console.log("connected");
    },
    onClose() {
      console.log("disconnected");
    },
  });

  return (
    <div>
      <ul>
        {messages.map((msg, i) => (
          <li key={i}>{msg}</li>
        ))}
      </ul>
      <button onClick={() => socket.send("ping")}>Ping</button>
    </div>
  );
}

Connecting to the current origin

When host is omitted in a browser, the hook defaults to window.location.host, so you can connect without hard-coding a URL:
import { usePartySocket } from "partysocket/react";

function Presence() {
  const socket = usePartySocket({
    room: "presence",
    onMessage(event) {
      console.log(event.data);
    },
  });

  return null;
}

Toggling the connection with enabled

import { useState } from "react";
import { usePartySocket } from "partysocket/react";

function LiveUpdates() {
  const [live, setLive] = useState(true);

  const socket = usePartySocket({
    host: "my-worker.workers.dev",
    room: "updates",
    enabled: live,
    onMessage(event) {
      console.log(event.data);
    },
  });

  return (
    <button onClick={() => setLive((v) => !v)}>
      {live ? "Pause" : "Resume"} updates
    </button>
  );
}

Dynamic auth token in query parameters

import { useCallback } from "react";
import { usePartySocket } from "partysocket/react";

function SecureRoom({ token }: { token: string }) {
  // Stabilise the function reference with useCallback so that a new
  // render with the same token value doesn't trigger a reconnect.
  const getQuery = useCallback(() => ({ token }), [token]);

  const socket = usePartySocket({
    host: "my-worker.workers.dev",
    room: "secure",
    query: getQuery,
  });

  return <div>Connected as token {token}</div>;
}

Raw reconnecting WebSocket with useWebSocket

import { useWebSocket } from "partysocket/react";

function LiveFeed() {
  const socket = useWebSocket("wss://feed.example.com/stream", undefined, {
    onMessage(event) {
      console.log("feed:", event.data);
    },
  });

  return <button onClick={() => socket.send("subscribe")}>Subscribe</button>;
}

Async URL provider with useWebSocket

import { useWebSocket } from "partysocket/react";

function AuthenticatedFeed() {
  const socket = useWebSocket(
    async () => {
      const token = await fetchToken();
      return `wss://feed.example.com/stream?token=${token}`;
    },
    undefined,
    {
      onMessage(event) {
        console.log(event.data);
      },
    }
  );

  return null;
}

Build docs developers (and LLMs) love