# React

> A hook around join and leave: the room's state and peers as React state, and the cleanup that StrictMode needs.

jsflow has no React package and needs none: a room is an object with events, and a hook is the glue. This page shows the one pattern that matters, **join when the component mounts, leave when it unmounts, and mirror the room's state into React state**, and the three things that go wrong without it.

Load the SDK the way [Loading the SDK](https://jsflow.com/docs/guides/loading-the-sdk.md) describes; with Vite, webpack or Next it is `npm install jsflow-sdk` and an import, and the worker is bundled for you.

## The hook

```ts check title="useRoom.ts"
import { useEffect, useState } from 'react';
import {
  join,
  type JoinOptions,
  type PeerId,
  type Room,
  type State,
} from 'jsflow-sdk';

export function useRoom(options: JoinOptions) {
  const [room, setRoom] = useState<Room>();
  const [state, setState] = useState<State>('joining');
  const [peers, setPeers] = useState<PeerId[]>([]);
  const [error, setError] = useState<unknown>();

  useEffect(() => {
    let gone = false;
    let cleanup = () => {};
    join(options).then((r) => {
      // Unmounted while joining: there was no room to leave until now.
      if (gone) { r.leave(); return; }
      const onState = (s: State) => setState(s);
      const onPeer = () => setPeers(r.peers());
      const onError = (e: Error) => setError(e);
      r.on('state', onState);
      r.on('peer', onPeer);
      r.on('error', onError);
      setRoom(r);
      setState(r.state);
      setPeers(r.peers());
      cleanup = () => {
        r.off('state', onState);
        r.off('peer', onPeer);
        r.off('error', onError);
        r.leave();
      };
    }, (e) => { if (!gone) setError(e); });
    return () => { gone = true; cleanup(); };
  }, [options.app, options.room]);

  return { room, state, peers, error };
}
```

Use it in a component:

```tsx title="Lobby.tsx"
function Lobby() {
  const { room, state, peers, error } = useRoom({
    app: 'pk_…',
    room: 'lobby',
  });
  if (error) return <p>Could not join: {String(error)}</p>;
  if (!room) return <p>Joining…</p>;
  return <p>{state}: {peers.length + 1} here</p>;
}
```

## Why it is written this way

- **`leave()` needs a room, and a room exists only after `join()` resolves.** `join()` takes no abort signal. If the component unmounts first, the effect's cleanup runs before there is anything to leave, so the `gone` flag makes the `then` leave the room the moment it arrives.
- **React StrictMode mounts, unmounts and mounts again in development.** That is a join, a leave and a second join: two peers in the room. The first one leaves as soon as its join resolves, so other peers see an extra peer appear and disappear once. In production the component mounts once. Nothing in the hook needs to change for this.
- **Calling `join()` twice does not reject and does not share.** Each call is its own peer, with its own id. Put the `join()` in one place (this hook, or a context provider above the components that need the room), not in every component that reads the room.
- **Read the peers, do not count the events.** The `'peer'` event says that a peer went up or down; `room.peers()` says who is reachable now. Re-reading it in the handler cannot drift.
- **Initialise from the room.** `join()` resolves in the `'joining'` state, usually before any link is up, and events that arrive later are tasks of their own, so subscribing in the same `then` misses nothing. Setting the state from `r.state` and `r.peers()` covers the rest.
- **Remove each listener with the function you added.** `off(event, f)` takes the same name and the same function, so keep every handler in a variable, as above. The cleanup removes them first and then calls `leave()`: the `'left'` state arrives a moment later, and a hook that has already unsubscribed does not see it.
- **`'error'` means this room will never connect.** The worker could not set it up after `join()` resolved. Call `leave()` and `join()` again; in the hook, that is a change to the effect's inputs, or a key on the component.

## Messages

Subscribe to `'message'` in a hook of its own, so a component that only shows who is here does not re-render for every message. Keep the callback in a ref, so a new function on every render does not unsubscribe and resubscribe:

```ts check title="useMessages.ts"
import { useEffect, useRef } from 'react';
import { text, type PeerId, type Room } from 'jsflow-sdk';

export function useMessages(
  room: Room | undefined,
  onText: (from: PeerId, message: string) => void,
) {
  const latest = useRef(onText);
  latest.current = onText;
  useEffect(() => {
    if (!room) return;
    const f = (from: PeerId, data: Uint8Array) => {
      latest.current(from, text(data));
    };
    room.on('message', f);
    return () => { room.off('message', f); };
  }, [room]);
}
```

For what to put in messages, and how to keep many peers in step, see [Keeping state in sync](https://jsflow.com/docs/guides/keeping-state-in-sync.md) and [Presence](https://jsflow.com/docs/guides/presence.md). When the app uses join tickets, `options.ticket` is a function that fetches a fresh ticket for each `join()`; the hook calls it once per join, as the SDK does.

## States worth showing

`state` is the room's state, one of the values in [the lifecycle](https://jsflow.com/docs/concepts/lifecycle.md): show `'joining'` as a spinner, `'connected'` as normal, and `'away'` (a hidden page) as quiet. `'evicted'` and `'suspended'` carry more detail in their own events (`'evicted'` has the time the block ends); a hook that wants to show why can subscribe to them the same way as above.

Source: https://jsflow.com/docs/guides/react/
