Blog

WebSockets in React: one connection for many components

· Andrij Tkachenko · 11 min read

A browser window with six component boxes whose lines join into one cable, which runs out of the window to a server

In React, open one websocket for the whole app, in a provider near the root, and let each component subscribe to the messages it needs. A socket opened in the useEffect of each component gives one connection per component, and without a cleanup that closes it, every mount leaves one more open.

We built both in React 19.3 and measured them in Chromium against a small websocket server in Node.js, counting connections on the server and renders in the page. The code in this post is the code we ran, with what Strict Mode does to it, why the last message kept in state skips messages, and how a socket updates React Query.

One socket in one component

The first version most people write opens the socket in an effect:

TSX
function OrderStatus() {
    const [status, setStatus] = useState('');

    useEffect(() => {
        const ws = new WebSocket('wss://example.com/ws');
        ws.onmessage = (event) => setStatus(JSON.parse(event.data).status);
        return () => ws.close(); // the line that decides how many stay open
    }, []);

    return <p>{status}</p>;
}

We loaded it with and without the cleanup, and counted the connections on the server:

Setup Opened Open after
No cleanup, Strict Mode in development 2 2
Cleanup, Strict Mode in development 2 1
No cleanup, mounted 11 times 11 11
Cleanup, mounted 11 times 11 1
Either, one mount in a production build 1 1

In development, Strict Mode runs one extra setup and cleanup before the first real setup, so a missing cleanup shows at once. With the cleanup, the first socket closes while it is still connecting, and Chromium logs "WebSocket is closed before the connection is established". Our production build, with no second run, did not log it. Keep the cleanup and leave the warning: a ref that skips the second run hides the bug it reports, and the cleanup is also what closes the socket when a user leaves the screen.

Without it, a component on a route people open and leave keeps a socket from every visit. Ours had 11 open after 11 mounts, each one still receiving every message for a component no longer on the page.

Twenty components, twenty connections

A socket per component multiplies with the components. We put 20 of them on one page, each opening its own, in a production build:

  • 20 connections for one user. Every message the server sends to all of them arrives on that page 20 times, and a service that counts concurrent connections counts all 20.
  • Seconds before the last one opened. The WebSocket standard allows a client only one connection to a host in the connecting state at a time, so Chromium opened them one by one. The first dozen came about 12 ms apart, then Chromium spaced the rest further, up to a second and more each, and the 20th was open 3.5 to 5 seconds after the page loaded. The server played no part: a Node.js client opened 20 to it in 24 ms.

One connection in a provider

Open the socket once in a provider and let components subscribe by message type. The socket is kept in a plain class outside React state, so a message calls the handlers of the components that asked for it, and no other component renders:

TSX
// socket.tsx: one websocket for the whole app, shared by every component under the provider.
import { createContext, useContext, useEffect, useEffectEvent, useState, type ReactNode } from 'react';

type Handler = (data: any) => void;

class Socket {
    private ws: WebSocket | null = null;
    private handlers = new Map<string, Set<Handler>>();
    private retries = 0;
    private timer: ReturnType<typeof setTimeout> | undefined;
    private closed = false;

    constructor(private url: string) {
        this.open();
    }

    private open() {
        const ws = new WebSocket(this.url);
        this.ws = ws;
        ws.onopen = () => {
            this.retries = 0;
        };
        ws.onmessage = (event) => {
            const { type, data } = JSON.parse(event.data);
            this.handlers.get(type)?.forEach((handler) => handler(data));
        };
        ws.onclose = () => {
            if (this.closed) return; // closed by the provider: no reconnect
            // The browser never reconnects by itself: wait longer after each failure, at most 30 s.
            const delay = Math.min(30_000, 500 * 2 ** this.retries++) * (0.5 + Math.random() / 2);
            this.timer = setTimeout(() => this.open(), delay);
        };
    }

    on(type: string, handler: Handler) {
        if (!this.handlers.has(type)) this.handlers.set(type, new Set());
        this.handlers.get(type)!.add(handler);
        return () => {
            this.handlers.get(type)!.delete(handler);
        };
    }

    send(type: string, data: unknown) {
        if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ type, data }));
    }

    close() {
        this.closed = true;
        clearTimeout(this.timer);
        this.ws?.close();
    }
}

const SocketContext = createContext<Socket | null>(null);

export function SocketProvider({ url, children }: { url: string; children: ReactNode }) {
    const [socket, setSocket] = useState<Socket | null>(null);

    useEffect(() => {
        const s = new Socket(url);
        setSocket(s);
        return () => s.close();
    }, [url]);

    return <SocketContext.Provider value={socket}>{children}</SocketContext.Provider>;
}

// Calls handler for each message of this type, while the component is on the page.
export function useSocketEvent(type: string, handler: Handler) {
    const socket = useContext(SocketContext);
    const onMessage = useEffectEvent(handler);

    useEffect(() => {
        if (!socket) return;
        return socket.on(type, (data) => onMessage(data));
    }, [socket, type]);
}

export function useSend() {
    const socket = useContext(SocketContext);
    return (type: string, data: unknown) => socket?.send(type, data);
}

The server sends JSON such as {"type": "order-42", "data": {"status": "shipped"}}, and a component takes the type it needs:

TSX
function OrderStatus({ id }: { id: number }) {
    const [status, setStatus] = useState('');
    useSocketEvent(`order-${id}`, (data) => setStatus(data.status));
    return <p>{status}</p>;
}

// Near the root of the app:
<SocketProvider url="wss://example.com/ws">
    <App />
</SocketProvider>

With 20 such components on the page, the server saw 1 connection, open 43 ms after the page loaded. Mounted and unmounted 10 times, the components opened nothing more, as the socket belongs to the provider. In that code:

  • useEffectEvent, in React 19.2 and later, hands the effect the latest handler, so a component does not subscribe again on every render. On an older React, keep the handler in a ref and update it in an effect.
  • closed stops the reconnect when the provider closes the socket itself, in the Strict Mode cleanup or when the app unmounts. Without it, the onclose of that socket schedules a reconnect, and a socket opens that nothing closes.
  • The delay grows from half a second to 30 seconds, with a random part, so a server that restarts is not reached by every page at once. We stopped the server for one second under Strict Mode with 20 components, three times: each run ended with one connection, opened again 70 to 255 ms after the server was back, and the next message reached its component.
  • Effects never run on the server, so the provider also works in an app rendered on the server. On serverless hosting the websocket server needs a home of its own, which our post on websockets in Next.js explains.

To install this instead of writing it, the react-use-websocket package has a useWebSocket hook, and its README describes a share option that puts the components naming the same address on one socket, closed when the last of them unmounts. Reconnecting is off by default, until you pass shouldReconnect or retryOnError.

The last message in state skips messages

A shortcut often seen keeps the last message in the state of the provider and passes it down through context. Every component that reads the context renders for every message, and when messages come faster than React renders, some are never seen. We sent 100 messages meant for one of 20 components, in a production build:

Setup Renders, 100 sent 5 ms apart Seen, 100 sent at once
The last message in context 2,099 4
Subscriptions, as above 100 100

With context, all 20 components rendered for each message, and the one it was for rendered once more after its own update. Sent at once, React batched the state updates into a few renders, and the components saw only the message that was current at each of them: 96 of 100 never reached the effect that waited for them. With subscriptions, the handler ran for each of the 100, and React batched the updates of that one component into 18 renders.

For a status that only needs its latest value, skipping a message is harmless. For a chat, a counter or a list that adds what each message brings, it loses data, so handle each message in a handler and put only the result in state.

WebSockets with React Query

When the data comes from React Query (TanStack Query), let the socket change its cache. A message can tell it to fetch again, or carry the change itself:

TSX
const queryClient = useQueryClient();

useSocketEvent('order', (change) => {
    // Fetch the order again:
    queryClient.invalidateQueries({ queryKey: ['order', 42] });

    // Or write what the message carries into the cache:
    queryClient.setQueryData(['order', 42], (old: Order) => ({ ...old, status: change.status }));
});

We sent 20 updates 50 ms apart to one component, with staleTime: Infinity so the query fetched only when told to. With invalidateQueries the API got 21 requests, the first load and one per update. With setQueryData it got 1, the first load. Both ended showing the last status.

Invalidating suits a message that only names the order to fetch. Writing saves a request on every update, and needs the whole change in the message.

Past one page and one server

The provider above gives one connection per tab and a reconnect. An app also needs these, and each one is built outside React:

  • Nothing lost while reconnecting. send() above drops what is sent while the socket is down, and messages sent to the page in that time are gone. Ids, a log on the server and a replay after each reconnect fix that, and our post on WebSockets in JavaScript builds them.
  • More than one server process. Each process knows only its own connections, so messages cross a channel they share, as our post on websockets in Node.js shows.
  • Who may hear what. The server has to know the user of each connection, and refuse a type of message or a room that person may not read.
  • Who is online and who is typing. Online indicators and typing indicators each take a few more events and timers.

Once a server of yours answers on a public address, our WebSocket test connects to it from a browser and explains any close code.

React on WordPlus Cloud

With WordPlus Cloud, the browsers connect to its servers, and @wordplus/realtime/react gives React the provider and the hooks. Your server says who may join each room and sends events to it. In Express:

TypeScript
// server.ts: the app key, the secret and the local key come from the environment.
// ownerOf(), nameOf() and markShipped() are your own, and req.user comes from your sign-in middleware.
import express from 'express';
import { createRealtime } from '@wordplus/realtime/server';

const realtime = createRealtime({
    // What others see of a user. Without it, nobody shows as online.
    profile: async (user) => ({ name: await nameOf(user) }),
});

// The room of an order: its customer joins, nobody else. Its last 20 updates are kept for pages that reconnect.
realtime.room('order:{id}', async (user, { id }) => user !== null && (await ownerOf(id)) === user, { history: 20 });

const app = express();
app.use('/api/realtime', realtime.node((req) => req.user?.id ?? null)); // before express.json()
app.use(express.json());

app.post('/orders/:id/ship', async (req, res) => {
    await markShipped(req.params.id);
    await realtime.to(`order:${req.params.id}`).emit('updated', { status: 'shipped' });
    res.sendStatus(204);
});

In the page, RealtimeProvider connects once, and each component joins the rooms it shows:

TSX
import { useState } from 'react';
import { RealtimeProvider, useConnection, useOnline, useRoom } from '@wordplus/realtime/react';

export function App() {
    return (
        <RealtimeProvider>
            <Connection />
            <OrderStatus id={42} />
            <OrderBadge id={42} />
        </RealtimeProvider>
    );
}

function Connection() {
    const { connected } = useConnection();
    return connected ? null : <p>Reconnecting…</p>;
}

function OrderStatus({ id }: { id: number }) {
    const [status, setStatus] = useState('open');
    const order = useRoom(`order:${id}`, { updated: (data) => setStatus(data.status) });
    return <p>{status} {order.state === 'failed' && order.error}</p>;
}

function OrderBadge({ id }: { id: number }) {
    const [shipped, setShipped] = useState(false);
    useRoom(`order:${id}`, { updated: (data) => setShipped(data.status === 'shipped') });
    const { online } = useOnline([34]);
    return <span>{shipped ? 'Shipped' : 'Open'} {online[34] && '· Ann is online'}</span>;
}

We type-checked both files against @wordplus/realtime 1.2.0, the version on npm. Beyond the provider above:

  • One join for many components. OrderStatus and OrderBadge join the same room once, and the room is left when the last of them unmounts.
  • Nothing lost on a reconnect. The connection comes back by itself, useConnection() says when it is down, and a room with history gives a page that reconnects the events it missed, in order.
  • Rules on your server. A page joins order:42 only if the rule says yes for its user, and a refused join comes back as order.state === 'failed' with its reason.
  • Presence and typing as hooks. useOnline(), usePresence() and useTyping() read who is online, who is in a room and who is typing.
  • React Query too. A handler of useRoom() can call queryClient.setQueryData() as above.

Start with the React docs

The React page of the docs lists every hook, and getting started sets up the routes in Express, Next.js, Laravel, Django and the rest. Our WebSocket API page shows rooms, presence and events in each stack, and the apps page the rest of what WordPlus Cloud does.

WordPlus Cloud for Apps is priced by concurrent connections, starting from 1,000, billed monthly or yearly, and our post on realtime pricing explains how counting by the connection works. The numbers are in the apps pricing. Questions about your integration? Write to us.