React

This page builds the runners game from Engines and frameworks with React. It imports shared.ts from that page; read its Connecting and Teardown sections first.

IRT has no React package. The hooks below are short enough to copy into a project, and they’re all a React app needs: one that owns the connection, and two built on useSyncExternalStore that re-render a component when the room’s state changes.

React is for the UI around the game: the connection’s ready state, lists of players, a wallet, buttons. The game world changes dozens of times a second and is drawn every frame, so draw it imperatively, in a canvas or an engine, from an effect; don’t put positions in React state.

The hooks

// hooks.ts
import { type Calls, type ClientEntity, type ConnectInit, type IrtError, type Kind, type ReadyRoomClient, type ReadyState, RoomClient, type ValuesOf } from "@irtio/client";
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";

/**
 * Connects to the room at `url` while the component is mounted. `room` is set once the client
 * holds the room's full state, so `calls`, `send`, `state` and `private` are safe to use from
 * then on.
 */
export function useRoom<S extends Kind<any>, P extends Kind<any>, C extends Calls<any>>(url: string, init: Pick<ConnectInit<S, P, C>, "token" | "schema">) {
  const { token, schema } = init;
  const [room, setRoom] = useState<ReadyRoomClient<S, P, C>>();
  const [readyState, setReadyState] = useState<ReadyState>("connecting");
  const [error, setError] = useState<IrtError>();

  useEffect(() => {
    const client = new RoomClient<S, P, C>(url, { token, schema });
    setRoom(undefined);
    setReadyState("connecting");
    setError(undefined);
    const listening = new AbortController();
    const signal = listening.signal;
    const update = () => setReadyState(client.readyState);
    for (const type of ["waking", "reconnecting", "open"] as const) client.addEventListener(type, update, { signal });
    client.addEventListener(
      "close",
      (e) => {
        update();
        setError(e.error);
      },
      { signal },
    );
    client.ready.then(
      (room) => setRoom(room),
      // The close listener has set the error.
      () => {},
    );
    return () => {
      listening.abort();
      client.close();
    };
  }, [url, token, schema]);

  return { room, readyState, error };
}

/**
 * The entities of a kind the client sees. Re-renders when one enters or leaves, and when one
 * of `fields` changes, or any field when `fields` is left out.
 */
export function useEntities<K extends Kind<any>>(
  room: RoomClient<any, any, any> | undefined,
  kind: K,
  fields?: readonly (keyof ValuesOf<K> & string)[],
): readonly ClientEntity<K>[] {
  const key = fields?.join();
  const store = useMemo(() => {
    let snapshot: readonly ClientEntity<K>[] = room ? [...room.entities.all(kind)] : [];
    return {
      subscribe(notify: () => void) {
        if (!room) return () => {};
        let dirty = false;
        const offs = [
          room.entities.onEnter(kind, () => (dirty = true)),
          room.entities.onLeave(kind, () => (dirty = true)),
          room.entities.onChange(kind, (_e, changed) => {
            if (!fields || changed.some((f) => fields.includes(f))) dirty = true;
          }),
        ];
        // One snapshot per state update, however many entities it changed.
        const updated = () => {
          if (!dirty) return;
          dirty = false;
          snapshot = [...room.entities.all(kind)];
          notify();
        };
        room.addEventListener("update", updated);
        // Catches up with updates between the first render and this subscription.
        snapshot = [...room.entities.all(kind)];
        return () => {
          for (const off of offs) off();
          room.removeEventListener("update", updated);
        };
      },
      snapshot: () => snapshot,
    };
    // `key` stands for `fields`, which callers usually pass as a new array each render.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [room, kind, key]);
  return useSyncExternalStore(store.subscribe, store.snapshot);
}

/**
 * A value read from the room after each state update, such as `(r) => r.private.coins`.
 * `read` must return a primitive or an object that only changes when the value does.
 */
export function useRoomValue<R extends RoomClient<any, any, any>, T>(room: R | undefined, read: (room: R) => T): T | undefined {
  const subscribe = useCallback(
    (notify: () => void) => {
      room?.addEventListener("update", notify);
      return () => room?.removeEventListener("update", notify);
    },
    [room],
  );
  return useSyncExternalStore(subscribe, () => (room ? read(room) : undefined));
}
  • useRoom owns the client: it connects in an effect and closes it in its cleanup, so unmounting the component, or changing the room URL, leaves the room. Its listeners share one AbortController, aborted in the cleanup. It returns room only after ready, so children never see a client that throws on a call, and the client’s readyState for the rest, which waking shows while the room starts.
  • useEntities keeps one array per state update, as useSyncExternalStore needs: the same array until something changes, then a new one. The entities in it are the client’s own objects, read fresh on each render; a component wrapped in memo that gets an entity as a prop doesn’t re-render when its fields change, so pass it the fields instead.
  • useRoomValue re-reads after every state update and re-renders only when the value differs.

In development, StrictMode runs each effect twice: useRoom connects, closes and connects again. The first client closes before its connection has opened, so the router never sees two connections of one player and closes neither with 4012.

The app

// app.tsx
import { IrtError, type ReadyRoomClient, reloadForNewBuild } from "@irtio/client";
import { joinVoice, type Voice } from "@irtio/client/voice";
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";
import { useEntities, useRoom, useRoomValue } from "./hooks.js";
import { type Input, type Match, Runner, schema, stepper, type Wallet } from "./shared.js";

type ArenaRoom = ReadyRoomClient<typeof Match, typeof Wallet, typeof schema.calls>;

// Pixels per world unit.
const PX = 32;

export function App({ roomId }: { roomId: string }) {
  // Relative to the page's irt-project meta tag, such as https://rooms.irt.io/my-game/<roomId>.
  const { room, readyState, error } = useRoom(roomId, { schema });

  useEffect(() => {
    if (error?.name === "VersionError") reloadForNewBuild();
  }, [error]);

  if (error) return <p>{error.message}</p>;
  if (!room) return <p>{readyState === "waking" ? "Waking the room" : "Connecting"}</p>;
  return (
    <>
      {readyState === "reconnecting" && <p>Reconnecting</p>}
      <Arena room={room} />
      <Coins room={room} />
      <Players room={room} />
      <Talk room={room} />
    </>
  );
}

function Arena({ room }: { room: ArenaRoom }) {
  const canvas = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    const el = canvas.current!;
    const ctx = el.getContext("2d")!;
    const keys = new Set<string>();
    const down = (e: KeyboardEvent) => keys.add(e.key);
    const up = (e: KeyboardEvent) => keys.delete(e.key);
    addEventListener("keydown", down);
    addEventListener("keyup", up);

    const me = room.predict(stepper, {
      find: (r) => [...r.entities.all(Runner)].find((e) => e.owner === r.player),
      sample: (): Input => ({
        dx: (keys.has("ArrowRight") ? 1 : 0) - (keys.has("ArrowLeft") ? 1 : 0),
        dy: (keys.has("ArrowDown") ? 1 : 0) - (keys.has("ArrowUp") ? 1 : 0),
      }),
    });
    const others = room.interpolate(Runner, ["x", "y"]);

    const aim = (e: PointerEvent) => {
      const at = me.render(["x", "y"]);
      const rect = el.getBoundingClientRect();
      for (const r of room.entities.mine(Runner)) {
        r.angle = Math.atan2(e.clientY - rect.top - at.y * PX, e.clientX - rect.left - at.x * PX);
      }
    };
    el.addEventListener("pointermove", aim);

    let frame = 0;
    const draw = () => {
      ctx.clearRect(0, 0, el.width, el.height);
      const local = me.render(["x", "y"]);
      for (const r of room.entities.all(Runner)) {
        const mine = r.owner === room.player;
        const at = mine ? local : others.get(r);
        if (Number.isNaN(at.x)) continue;
        const x = at.x * PX;
        const y = at.y * PX;
        ctx.fillStyle = mine ? "#4cc9f0" : "#f72585";
        ctx.beginPath();
        ctx.arc(x, y, 12, 0, 2 * Math.PI);
        ctx.fill();
        ctx.strokeStyle = "#fff";
        ctx.beginPath();
        ctx.moveTo(x, y);
        ctx.lineTo(x + Math.cos(r.angle) * 20, y + Math.sin(r.angle) * 20);
        ctx.stroke();
      }
      frame = requestAnimationFrame(draw);
    };
    frame = requestAnimationFrame(draw);

    return () => {
      cancelAnimationFrame(frame);
      el.removeEventListener("pointermove", aim);
      removeEventListener("keydown", down);
      removeEventListener("keyup", up);
      me.stop();
    };
  }, [room]);

  return <canvas ref={canvas} width={960} height={640} />;
}

function Coins({ room }: { room: ArenaRoom }) {
  const coins = useRoomValue(room, (r) => r.private.coins);
  const [message, setMessage] = useState("");

  async function buy() {
    try {
      await room.calls.buy({ item: "dash" });
      setMessage("");
    } catch (e) {
      if (e instanceof IrtError) setMessage(e.message);
      else throw e;
    }
  }

  return (
    <p>
      {coins} coins <button onClick={() => void buy()}>Buy a dash</button> {message}
    </p>
  );
}

function Players({ room }: { room: ArenaRoom }) {
  const runners = useEntities(room, Runner, ["owner"]);
  return (
    <ul>
      {runners.map((r) => (
        <li key={r.id}>{r.owner === room.player ? `${r.owner} (you)` : r.owner}</li>
      ))}
    </ul>
  );
}

function Talk({ room }: { room: ArenaRoom }) {
  const [voice, setVoice] = useState<Voice>();
  const subscribe = useCallback(
    (notify: () => void) => {
      room.addEventListener("peers", notify);
      return () => room.removeEventListener("peers", notify);
    },
    [room],
  );
  const speakers = useSyncExternalStore(subscribe, () => room.peers.speakers);

  useEffect(() => {
    const v = joinVoice(room, {
      position(player) {
        const r = [...room.entities.all(Runner)].find((e) => e.owner === player);
        return r && { x: r.x, y: r.y };
      },
      range: 12,
    });
    setVoice(v);
    return () => void v.disconnect();
  }, [room]);

  return (
    <p>
      <button onClick={() => void voice?.enableMic()}>Talk</button> Hearing: {speakers.join(", ") || "no one"}
    </p>
  );
}
// main.tsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { App } from "./app.js";

createRoot(document.querySelector("#root")!).render(
  <StrictMode>
    <App roomId={new URLSearchParams(location.search).get("room") ?? "arena"} />
  </StrictMode>,
);

How it fits together:

  • App renders by ready state. Until useRoom returns a room, it shows connecting or waking; after a close it shows the error, and reloads on a VersionError, 4004. Reconnects keep the room, so the game stays mounted with a banner on top.
  • Arena draws in an effect. The prediction, the interpolator, the input handlers and the animation frame are created when it mounts and stopped in its cleanup. Nothing in it sets React state, so the canvas redraws every frame without a single re-render.
  • Aim writes the owned runner. The pointer handler sets angle on entities.mine(Runner), and the draw loop reads it back from the entity: the client keeps the owner’s value, so the local aim line turns at once.
  • Coins re-renders once per change. useRoomValue reads room.private.coins after each state update; the buy call’s reply isn’t needed for the label, since the room’s change to the wallet arrives with the next state update.
  • Players ignores movement. With ["owner"], it re-renders when a runner enters or leaves, not 30 times a second as runners move.
  • Talk owns the voice. It joins in an effect and disconnects in the cleanup, and room.peers.speakers is a new array only when the room changes who this player hears, so it works as a snapshot as is.

An interpolator lives as long as its RoomClient, so each mount of Arena adds one. That’s harmless for a component that mounts once per room; one that mounts and unmounts often should get its interpolator from the component that calls useRoom.

Common mistakes

  • Positions in React state. Setting state on every state update re-renders 30 times a second and still stutters, because it isn’t interpolated. Draw from the frame loop.
  • Creating the client in useMemo or during render. React may call either twice and drop one result, leaving a connected client nobody closes. Create it in an effect, as useRoom does.
  • Creating a prediction in useMemo. The same goes for predict: a dropped one keeps sampling and sending inputs. Create it in an effect and stop() it in the cleanup.
  • A new array from getSnapshot on every call. useSyncExternalStore then re-renders forever. Return the same array until something changed, as useEntities does.
  • Passing useRoom a new schema each render. The effect depends on the schema; import it from the shared module so it stays the same object.