日本語

How to Wrap a WebSocket Connection in a Custom React Hook

​​React​custom hooks,Playwright,TypeScript,useEffect,useEffectEvent,WebSocket

When you use WebSocket in React, putting the connection and its cleanup into one custom hook means a component only has to call useWebSocket(url, { onMessage }). Inside the hook, useEffect opens the connection and closes it in the cleanup. The handler for incoming messages is wrapped in useEffectEvent. When the connection drops on its own, rather than being closed by the hook, the hook reconnects with a growing wait between attempts.

In my test setup, I built a small chat screen with a WebSocket server on Node.js (the ws package), drove Chromium with Playwright, and checked the number of connections the server received along with what the browser did.

Note

The test setup was Ubuntu 24.04 and Node.js 22.22.0. I used react and react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, esbuild 0.28.2, and ws 8.22.0. I type-checked the .tsx files with tsc, transpiled them with esbuild, and ran Chromium 141 through Playwright 1.56.1. The server ran on the same machine, and I connected with ws:// (unencrypted). I did not test wss://, real network disconnections, or other browsers.

Point

Create the connection inside useEffect and always close it in the cleanup. Wrap the message handler in useEffectEvent and keep it out of the dependency array. Do not reconnect when the cleanup closed the socket, and only send while the connection is open.

The Whole WebSocket Hook

This is the hook I used in the test. It returns the connection status (status) and a function for sending (send).

ts
import { useCallback, useEffect, useEffectEvent, useRef, useState } from 'react';

export type WebSocketStatus = 'connecting' | 'open' | 'closed';

export type WebSocketOptions = {
  onMessage?: (event: MessageEvent) => void; // Called when a message arrives
  reconnect?: boolean; // Whether to reconnect after an unexpected close
  retryDelay?: number; // Wait before the first reconnect attempt (ms). Doubles after each failure
  maxRetryDelay?: number; // Upper limit for the wait (ms)
};

export function useWebSocket(
  url: string,
  { onMessage, reconnect = true, retryDelay = 500, maxRetryDelay = 8000 }: WebSocketOptions = {},
) {
  const [status, setStatus] = useState<WebSocketStatus>('connecting');
  const socketRef = useRef<WebSocket | null>(null);

  // Calls the latest onMessage at the time a message arrives, without reconnecting
  const handleMessage = useEffectEvent((event: MessageEvent) => {
    onMessage?.(event);
  });

  useEffect(() => {
    let socket: WebSocket;
    let timer: ReturnType<typeof setTimeout> | undefined;
    let attempt = 0; // Number of consecutive failures
    let disposed = false; // Whether the cleanup has run

    function connect() {
      setStatus('connecting');
      socket = new WebSocket(url);
      socketRef.current = socket;
      socket.onopen = () => {
        attempt = 0;
        setStatus('open');
      };
      socket.onmessage = (event) => handleMessage(event);
      socket.onclose = () => {
        if (disposed) return; // Do not reconnect when we closed it ourselves
        socketRef.current = null;
        setStatus('closed');
        if (!reconnect) return;
        const delay = Math.min(retryDelay * 2 ** attempt, maxRetryDelay);
        attempt++;
        timer = setTimeout(connect, delay);
      };
    }

    connect();
    return () => {
      disposed = true;
      clearTimeout(timer);
      socketRef.current = null;
      socket.close();
    };
  }, [url, reconnect, retryDelay, maxRetryDelay]);

  // Sends only while connected. Returns false if the message could not be sent
  const send = useCallback((data: string) => {
    const socket = socketRef.current;
    if (socket?.readyState !== WebSocket.OPEN) return false;
    socket.send(data);
    return true;
  }, []);

  return { status, send };
}

The caller passes the URL and the handler for incoming messages. The following is taken from the chat screen I used in the test. Selecting a room changes the room in the URL.

tsx
const { status, send } = useWebSocket(`${baseUrl}/?room=${room}`, {
  onMessage: (event) => setMessages((m) => [...m, String(event.data)]),
});

function handleSend() {
  if (send(text)) {
    setText('');
    setNotice('');
  } else {
    setNotice('つながっていないので、送れませんでした');
  }
}

The test server sends a "joined room a" message when a client connects, and returns each received message prefixed with "echo: ". The following is the result after sending "hello" and then switching to room b.

text
送ったあとのメッセージ: ["部屋 a に入りました","echo: こんにちは"]
部屋を b にしたあとのメッセージ: ["部屋 a に入りました","echo: こんにちは","部屋 b に入りました"]
サーバーから見た部屋 a の接続: [{"id":1,"open":true,"closed":true,"code":1005}]
サーバーから見た部屋 b の接続: [{"id":2,"open":true,"closed":false,"code":null}]

When the URL changed, the cleanup closed the room a connection, and a new connection to room b opened. After the page was closed, no room b connection remained. The code 1005 is "No Status Received" on MDN's CloseEvent.code page. The cleanup calls close() without a code, so the server receives no close code.

The top bar shows an operation counter such as "operation 1 of 4". Sending "hello" returns an echo. Stopping the server changes the status to "disconnected". Pressing send while stopped shows a "not connected, so the message could not be sent" notice. Starting the server changes the status back to "connected", and sending again delivers the message. (The labels in the image are in Japanese.)
Sending, stopping the server, sending while stopped, and sending after starting the server and reconnecting

Wrap the Message Handler in useEffectEvent

If the caller passes a new function on every render, putting onMessage in the useEffect dependency array reconnects on every render. For comparison, I built a hook that puts onMessage directly in the dependency array.

ts
useEffect(() => {
  const socket = new WebSocket(url);
  socket.onopen = () => setStatus('open');
  socket.onmessage = (event) => onMessage(event);
  socket.onclose = () => setStatus('closed');
  return () => socket.close();
}, [url, onMessage]);

I built a screen that stores received messages in state, once with this version and once with the hook from this article. Both connect to the same room, deps. I counted the connections over the first two seconds after opening.

text
deps: 開いてから2秒のあいだにサーバーが受けた接続 175、そのうち閉じた接続 175、表示「部屋 deps に入りました(入力欄: )」
deps: 同じ2秒のあいだにページで作った WebSocket 356、そのうち open まで進んだもの 177、open する前に閉じたもの 178、届いたメッセージ 147
effect-event: 開いてから2秒のあいだにサーバーが受けた接続 1、そのうち閉じた接続 0、表示「部屋 deps に入りました(入力欄: )」

With the dependency-array version, the page created 356 WebSocket objects in two seconds, and the server received 175 connections. All 175 server-side connections were already closed when I counted. About half of the WebSocket objects were closed before they connected. In this version, each re-render caused by a state change such as setStatus produces a new onMessage function, which reruns the effect and creates a new connection. That in turn changes state again. The hook in this article kept a single connection for the two seconds.

Next I typed abc into the input field and then had the server send a message. The result:

text
effect-event: 入力欄に abc と打ってからサーバーが送ったあと、サーバーが受けた接続 1、表示「お知らせ(入力欄: abc)」

The connection stayed at one while I was typing, and the handler read the latest input value (abc) when the message arrived. The official documentation example for passing event handlers to custom hooks also wraps the handler in useEffectEvent, noting that putting a received handler in the dependency array reconnects on every render. As the useEffectEvent caveats say, the wrapped function must be called from inside an effect, and it becomes a different function on every render. This hook also calls it from the onmessage handler set up inside the effect. For useEffectEvent, see my earlier article, "How to read the latest value without re-running an effect with React's useEffectEvent."

Do Not Reconnect After the Cleanup Closes the Socket

Reconnecting starts in onclose. However, onclose also fires when the cleanup calls close(). So in this hook, the cleanup sets disposed to true, and the reconnect is skipped in that case. For comparison, I also built a hook without this check, which always reconnects in onclose.

ts
function connect() {
  socket = new WebSocket(url);
  socket.onopen = () => setStatus('open');
  socket.onclose = () => {
    setStatus('closed');
    setTimeout(connect, 500);
  };
}
connect();
return () => socket.close();

I connected, then removed the component with a button, waited two seconds, and counted the connections that were open on the server:

text
guard: サーバーが受けた接続 1、いま開いている接続 0
no-guard: サーバーが受けた接続 2、いま開いている接続 1

The hook from this article (first line) left no connection behind after unmount. The version without the check (second line) reconnected in onclose after the close, so one connection stayed open even though the component had been removed. The cleanup also cancels any scheduled reconnect with clearTimeout.

When the Connection Drops, Reconnect with a Growing Wait

After connecting, I stopped the server, waited a little over 13 seconds, and restarted it. The following shows each WebSocket created on the page and when it was created.

text
  1回目: ひとつ前が閉じてから 501ms 後に作成、結果 close code 1006
  2回目: ひとつ前が閉じてから 1001ms 後に作成、結果 close code 1006
  3回目: ひとつ前が閉じてから 2001ms 後に作成、結果 close code 1006
  4回目: ひとつ前が閉じてから 4001ms 後に作成、結果 close code 1006
  5回目: ひとつ前が閉じてから 8000ms 後に作成、結果 open
最初に切れた接続の close: {"code":1006,"wasClean":false}
つながったあとにもう一度切ったとき: 閉じてから 501ms 後に作成

The wait grew from 0.5 seconds, doubling each time, up to the 8-second limit. The fifth attempt connected to the restarted server. Because attempt is reset to 0 once the connection opens, the next reconnect after another drop happened 0.5 seconds later. Every failure while the server was down had close code 1006. According to the same MDN CloseEvent.code page, 1006 means the connection was lost without a closing handshake (a close frame). My test server dropped the clients without a closing handshake when it stopped.

Growing the wait means that even when the server stays down for a long time, the hook does not keep trying every 0.5 seconds. Unless reconnect is set to false, this hook always reconnects except when the hook itself closed the socket. That includes cases where the server closes the connection with a closing handshake. If you need to distinguish a deliberate close by the server from a drop and skip reconnecting in the first case, branch on event.code, which onclose receives.

Do Not Send While Not Connected

When a browser WebSocket's send is called while not connected, the behavior depends on the state. This is the result with a raw WebSocket, without the hook:

text
素の WebSocket: {"readyStateAtStart":0,"sendWhileConnecting":"InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.","readyStateAfterClose":3,"sendAfterClose":"エラーなし","bufferedAmountAfterClose":3}

While connecting (readyState 0), it threw InvalidStateError. After closing (readyState 3), it did not throw, and only bufferedAmount increased. The MDN WebSocket.send() page also says that in CONNECTING it throws an exception, and in CLOSING and CLOSED it silently discards the data. Since send after closing raises no error, you cannot tell that the message was not sent.

So the hook's send sends only when readyState is OPEN, and returns false otherwise. This is the result of pressing send while the server was stopped:

text
止まっているあいだに送信を押した結果: {"status":"切断","notice":"つながっていないので、送れませんでした","text":"届く?"}

The caller receives false, shows the "could not be sent" notice, and leaves the text in the input field. This is the result after restarting the server, connecting again, and pressing send with the leftover text still in the field:

text
つなぎ直したあとの入力欄: "届く?"
つなぎ直したあとのメッセージ: ["部屋 a に入りました","部屋 a に入りました","部屋 a に入りました","echo: 届く?"]

The leftover "Will this arrive?" was delivered. On this screen, the "could not be sent" notice is cleared the next time a send succeeds, so it stays visible for a while after reconnecting, as in the GIF above.

In Development with StrictMode, the Connection Is Created Twice

I compared a development build with and without StrictMode:

text
StrictMode なし: ページで作った WebSocket [{"opened":true}]、サーバーが受けた接続 1、いま開いている接続 1、画面のメッセージ ["部屋 a に入りました"]
StrictMode あり: ページで作った WebSocket [{"opened":false,"code":1006},{"opened":true}]、サーバーが受けた接続 2、いま開いている接続 1、画面のメッセージ ["部屋 a に入りました"]

With StrictMode, two WebSocket objects were created on the page, and the server received two connections. The first was closed by the cleanup before it connected, and the console showed the warning "WebSocket is closed before the connection is established." Even so, the last connection was the only one open, and the greeting appeared only once on screen.

The official documentation on effects running twice in development describes this as intended behavior that only happens in development. It says that if the cleanup is done correctly, the result should be indistinguishable from a single run, and that fixing it with a ref to skip the second run is the wrong approach. If the server log shows two connections during development but only one is open, the hook's cleanup is working.

With the Hook, Every Component Behaves the Same

Point

With one useWebSocket hook, the same rules apply in every component: close and reconnect when the URL changes, close on unmount, reconnect with a growing wait when the connection drops, and do not send while not connected. The caller only has to decide what to do with incoming messages and what to show when send returns false.

​Posted by 86