Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 36 ยท Integration with Frameworks

Browser Clients, React and Vue

Use the Socket.IO client in plain JavaScript, React and Vue: one shared socket, safe cleanup of listeners, a connection store, and reconnection-aware UI.

On the browser side the job is small but easy to get wrong: create one socket, attach listeners once, remove them when a component goes away, and keep the UI in step with connection status. The patterns are the same in plain JavaScript, React, Vue, Svelte or Angular. Only the place where you subscribe and unsubscribe changes.

The socket.io-client package is not available in the runner on this site. Framework code is read-only. The runnable examples are framework-free JavaScript stand-ins (a fake socket and a tiny store) that show the logic those wrappers use.

Getting the client

Three ways to load it:

HTML
<!-- 1. served by your Socket.IO server -->
<script src="/socket.io/socket.io.js"></script>
<script>
  const socket = io();
</script>
JavaScript
// 2. a bundler (Vite, webpack, ...): npm install socket.io-client
import { io } from "socket.io-client";
export const socket = io("https://api.example.com", { autoConnect: false });
HTML
<!-- 3. an ES module from a CDN, pinned to a version -->
<script type="module">
  import { io } from "https://cdn.socket.io/4.8.1/socket.io.esm.min.js";
  const socket = io();
</script>

With no URL, io() connects to the host that served the page. With a URL, the server must allow your origin (CORS).

One socket, created once

The classic bug is creating a socket inside a component. Every render or mount opens another connection, and the server soon sees dozens of sockets per tab. Put the socket in its own module, so the module system guarantees a single instance:

JavaScript
// socket.js
import { io } from "socket.io-client";

export const socket = io(import.meta.env.VITE_SOCKET_URL, {
  autoConnect: false,   // connect when the user is ready (e.g. after login)
  auth: (cb) => cb({ token: localStorage.getItem("token") }),
});

autoConnect: false lets you decide when to connect: after authentication, or only on pages that need real-time features. Call socket.connect() and socket.disconnect() explicitly.

Listeners: subscribe and unsubscribe in pairs

socket.on(event, handler) adds a listener and never removes it on its own. Mount a component three times and you have three listeners, producing three renders and duplicated messages. Always pair on with off, using the same function reference:

JS Listener leaks versus cleanup (fake socket)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The leaky component reacts three times to one message. This is why every framework wrapper has the same shape: subscribe in the "mounted" hook, unsubscribe in the "unmounted" hook.

React

JSX
import { useEffect, useState } from "react";
import { socket } from "./socket";

export function useSocketEvent(event, handler) {
  useEffect(() => {
    socket.on(event, handler);
    return () => socket.off(event, handler);
  }, [event, handler]);
}

export function ConnectionStatus() {
  const [isConnected, setIsConnected] = useState(socket.connected);

  useEffect(() => {
    const onConnect = () => setIsConnected(true);
    const onDisconnect = () => setIsConnected(false);
    socket.on("connect", onConnect);
    socket.on("disconnect", onDisconnect);
    return () => {
      socket.off("connect", onConnect);
      socket.off("disconnect", onDisconnect);
    };
  }, []);

  return <p>{isConnected ? "Online" : "Reconnecting..."}</p>;
}

export function Chat() {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    const onMessage = (m) => setMessages((prev) => [...prev, m]);
    socket.on("message", onMessage);
    return () => socket.off("message", onMessage);
  }, []);

  const send = (text) => socket.emit("message", text);
  return <ul>{messages.map((m, i) => <li key={i}>{m}</li>)}</ul>;
}

Two React details matter. The useEffect cleanup runs in React's StrictMode double-invocation in development, which is precisely what exposes missing cleanup. And handlers must not close over stale state: use the functional form of setState (prev => ...) as above. Where possible, use useSyncExternalStore to subscribe to an external store, which is built for this.

Vue

JavaScript
// useSocket.js (Vue 3 composition API)
import { ref, onMounted, onBeforeUnmount } from "vue";
import { socket } from "./socket";

export function useConnection() {
  const connected = ref(socket.connected);
  const onConnect = () => (connected.value = true);
  const onDisconnect = () => (connected.value = false);

  onMounted(() => {
    socket.on("connect", onConnect);
    socket.on("disconnect", onDisconnect);
  });
  onBeforeUnmount(() => {
    socket.off("connect", onConnect);
    socket.off("disconnect", onDisconnect);
  });
  return { connected };
}

In Svelte you subscribe in onMount and return a cleanup function; in Angular you wrap events in an RxJS Observable (fromEvent-like) and unsubscribe in ngOnDestroy. The structure is identical.

A framework-free store

A cleaner design keeps socket events out of components entirely. A store subscribes to the socket once, holds state, and lets components subscribe to the store. Frameworks then only read state.

JS A tiny connection and message store

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The store has exactly one set of socket listeners no matter how many components exist, which removes the leak risk. In React this is useSyncExternalStore(store.subscribe, store.getState); in Vue it is a reactive object; in Svelte it is a store.

Practical tips

  • Optimistic UI with acks: show the message immediately, mark it "sending", and confirm when the acknowledgement arrives.
  • Show connection state (connect, disconnect, connect_error) and disable send buttons while offline.
  • Refresh tokens on reconnect with the function form of auth, so a reconnection after expiry uses a new token (reconnection).
  • Server-side rendering: create the socket only in the browser (inside effects or onMounted), never during server rendering.
  • Do not put the socket object in framework state: keep it as a module constant; put the data it produces in state.
  • Disconnect when leaving: call socket.disconnect() on logout, or the old identity stays connected.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should the Socket.IO client instance be created in a React or Vue app?

    A module-level instance guarantees a single connection. Creating sockets in components multiplies connections.
  2. 2. What happens if a component calls socket.on in its mount hook and never calls socket.off?

    Listeners stay registered after the component unmounts, so each new mount adds another and handlers fire repeatedly.
  3. 3. What does autoConnect false let you do?

    The socket is created but idle until you call connect, which is useful when credentials are needed first.
  4. 4. Why use the function form of auth?

    The callback runs for every (re)connection, so you can read the latest token each time.

Summary

  • Create the socket once in its own module; use autoConnect: false when you need to control timing.
  • Always remove listeners with off (same function reference) when a component is destroyed.
  • Wrap subscriptions in a store or hook so components stay simple.
  • Show connection state and handle optimistic UI with acknowledgements.
  • Create sockets only in the browser, not during server-side rendering.

Next: Binary Data and Compression