Reconnection and connection state in the UI

Real users lose connection constantly. A tab going to the background, a phone switching networks, a laptop waking from sleep. A good realtime UI detects the disconnect, tries to reconnect with backoff, and shows the user honestly what is happening.

src/ws.ts
typescript
export function connectWithReconnect(token: string, onEvent: (data: any) => void) {
  let attempt = 0;
  let ws: WebSocket;

  function open() {
    ws = new WebSocket('ws://localhost:3000?token=' + token);

    ws.onopen = () => {
      attempt = 0; // reset on success
    };

    ws.onmessage = (e) => onEvent(JSON.parse(e.data));

    ws.onclose = () => {
      attempt++;
      const delay = Math.min(1000 * 2 ** attempt, 30_000);
      setTimeout(open, delay);
    };
  }

  open();
  return () => ws && ws.close();
}

Reconnect with exponential backoff, capped at 30 seconds.

Add a small indicator to the UI that shows the connection state. A green dot when connected, a yellow pulse when reconnecting, a red alert when disconnected for too long. Users are patient when they know what is happening. They get angry when the app pretends nothing is wrong.

Reconnect lifecycle

Each close triggers a backed-off retry. Success resets the counter. The UI mirrors every transition.

Quiz: Quiz

Loading practice…

Checkpoint: Realtime UI checkpoint

Loading practice…