Skip to main content

WebSocket chat

A chat room connected to a public WebSocket echo server. The server sends every message back, so what you see in the list has made the full trip: emitter, server, listener.

intermediaterealtimeuseListeneruseEmitter
import { useEmitter, useListener } from "@hyper-fetch/react";
import { type FormEvent, useState } from "react";

import { type ChatMessage, onChatMessage, sendChatMessage, socket } from "./api";

const author = `guest-${Math.floor(Math.random() * 1000)}`;

export const App = () => {
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [log, setLog] = useState<string[]>([]);
const addLog = (entry: string) =>
setLog((prev) => [`${new Date().toLocaleTimeString()} ${entry}`, ...prev].slice(0, 6));

// Subscribes while the component is mounted. `connected` and `connecting` follow the socket.
const { connected, connecting, onEvent, onConnected, onDisconnected, onReconnecting } = useListener(onChatMessage);
const { emit } = useEmitter(sendChatMessage);

onEvent(({ data }) => setMessages((prev) => [...prev, data]));
onConnected(() => addLog("connected"));
onDisconnected(() => addLog("disconnected"));
onReconnecting(({ attempts }) => addLog(`reconnecting, attempt ${attempts}`));

const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const form = event.currentTarget;
const text = String(new FormData(form).get("text"));
form.reset();
emit({ payload: { id: crypto.randomUUID(), author, text, sentAt: Date.now() } });
};

let status = "Disconnected";
if (connected) status = "Connected";
else if (connecting) status = "Connecting...";

return (
<main className="container">
<hgroup>
<h1>WebSocket chat</h1>
<p>Messages go to a public echo server and come back through the listener.</p>
</hgroup>
<div className="chat-layout">
<article>
<header className="toolbar">
<strong aria-busy={connecting && !connected}>{status}</strong>
<div role="group">
<button type="button" className="outline secondary" onClick={socket.disconnect} disabled={!connected}>
Disconnect
</button>
<button type="button" className="outline" onClick={socket.reconnect} disabled={connected}>
Reconnect
</button>
</div>
</header>
<ul className="messages">
{messages.length === 0 && <li className="muted">No messages yet. Say hi.</li>}
{messages.map((message) => (
<li key={message.id}>
<small className="muted">
{message.author} · {new Date(message.sentAt).toLocaleTimeString()}
</small>
<p>{message.text}</p>
</li>
))}
</ul>
<form onSubmit={handleSubmit} role="group">
<input name="text" placeholder={connected ? "Write a message" : "Not connected"} required />
<button type="submit" disabled={!connected}>
Send
</button>
</form>
</article>
<article>
<h6>Connection log</h6>
{log.length === 0 && <p className="muted">Nothing yet. Try Disconnect and Reconnect.</p>}
<ol className="log">
{log.map((entry, index) => (
<li key={log.length - index}>{entry}</li>
))}
</ol>
</article>
</div>
</main>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/websocket-chat hyper-fetch-react-websocket-chat && cd hyper-fetch-react-websocket-chat && npm install && npm run dev
What it shows
  1. createSocketClient with the WebsocketAdapter opens one connection that every listener and emitter shares.
  2. Typed listeners and emitters describe a topic and the shape of its messages once.
  3. useListener subscribes while the component is mounted and reports connected and connecting.
  4. Reconnects happen on their own after a dropped connection, and disconnect() / reconnect() control them by hand.

How it works​

  1. api.ts creates the socket with createSocketClient({ url, adapter: WebsocketAdapter(), reconnectTime }). It connects as soon as it is created.

  2. onChatMessage and sendChatMessage use the same topic. The adapter sends { topic, data } as JSON and passes each incoming frame to the listeners of its topic. Servers with another message format can use the encode and decode adapter options.

  3. App calls useListener(onChatMessage) and appends every message in onEvent:

    const { connected, connecting, onEvent } = useListener(onChatMessage);
    onEvent(({ data }) => setMessages((prev) => [...prev, data]));
  4. useEmitter(sendChatMessage) returns emit, which sends the typed payload: emit({ payload: message }).

  5. onConnected, onDisconnected and onReconnecting fill the connection log. Disconnect calls socket.disconnect(), which keeps the socket closed. Reconnect calls socket.reconnect(). When the server drops the connection instead, the adapter tries again every reconnectTime milliseconds.

When to use it
  • Chats, comments and presence that update for everyone at once.
  • Collaborative tools and live dashboards with a WebSocket backend.
  • Any server that pushes messages and also accepts them from the client.

Summary

One socket client, a listener and an emitter for the same topic make a chat. useListener and useEmitter bind them to React and expose the connection state, while the adapter handles reconnects.