FG
📱 Mobile & Cross-Platformproduction

Socket.IO singleton creates duplicate connection after network disconnect

Fresh6 days ago
Mar 14, 20260 views
Confidence Score73%
73%

Problem

A Socket.IO singleton has a connection guard: `if (this.socket && this.isConnected) return`. When the network drops, `isConnected` becomes false but `this.socket` still exists. A reconnect attempt passes the guard, creating a second socket alongside the disconnected first one. The app now has two simultaneous sockets, causing duplicate event handlers, double events, and memory leaks.

Unverified for your environment

Select your OS to check compatibility.

1 Fix

Canonical Fix
High Confidence Fix
69% confidence85% success rate8 verificationsLast verified Mar 14, 2026

Fix the connection guard to check socket existence, not connected state

Low Risk

The guard `if (this.socket && this.isConnected)` allows a new socket when the old one exists but is disconnected, creating a duplicate.

69

Trust Score

8 verifications

85% success
  1. 1

    Change the guard to check socket existence only

    In your Socket.IO singleton:

    typescript
    // ❌ Allows duplicate when socket exists but is disconnected
    connect() {
      if (this.socket && this.isConnected) return
    
    // ✅ Never create a second socket if one exists at all
    connect() {
      if (this.socket) return  // one socket per instance, always
  2. 2

    Let Socket.IO handle reconnection internally

    Socket.IO has built-in reconnection logic. Don't create a new socket on disconnect — let the existing socket reconnect itself:

    typescript
    const socket = io(url, {
      transports: ['websocket'],
      reconnection: true,
      reconnectionAttempts: 10,
      reconnectionDelay: 1000,
    })
  3. 3

    Disconnect properly before creating a new socket if needed

    If you need to force a fresh connection (e.g. on logout):

    typescript
    disconnect() {
      if (this.socket) {
        this.socket.disconnect()
        this.socket = null
      }
    }

Validation

After a network disconnect, exactly one socket connection is active. No duplicate event handler calls.

Verification Summary

Worked: 8
Partial: 3
Failed: 2
Last verified Mar 14, 2026

Sign in to verify this fix

Environment

Product
Socket.IO (Node.js / React Native)
Environment
production

Submitted by

AC

Alex Chen

2450 rep

Tags

socketiosingletonreconnectduplicate-connectionmemory-leak