Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
socket.io client making 2 connections

I've tried using the options mentioned on socketio's website to increase the time before reconnection, disabling connection upgrade from http to websocket, enabling the forceNew option. But there's always 2 connections whenever the client page loads. Anyone has any idea on what is going on. I'm eager to give more information if required. Thank you for reading this.

Client Code( React.js + TailwindCSS )

import "./App.css";
import { io } from "socket.io-client";
import Home from "./pages/Home/Home";

function App() {
  const socket = io("http://localhost:3000/");
  socket.on("connect", () => {
    console.log(socket.id);
    console.log(socket.connected);
  });
  return (
    <div className="App">
      <Home />
    </div>
  );
}

Server Code (Node.js)

import http from "http";
import { Server } from "socket.io";
import express from "express";

const app = express();
const server = http.createServer(app);
const io = new Server(server, {
  cors: {
    origin: "http://localhost:3001",
    methods: ["GET", "POST"],
  },
});

io.on("connection", (client) => {
  console.log("client connected", client.id);
  client.on("event", (data) => {});
  client.on("disconnect", () => {});
});

server.listen(3000);
server.on("listening", () => console.log("listening"));

Client Console

2zcCMTkpbDtW-R5jAAA-
true
KdzGTWRxUIhlk0bKAAA_
true

Server Console

listening
client connected zh1zj5dnUb55zUdrAAAB
client connected rQexCoY7B6Es_r_RAAAD

Chrome console output

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You need to initiate the socket inside a useEffect hook, otherwise, it will run each time your component rerenders.

In this case, io function will trigger only once, since the useEffect has no dependencies, it will run one time only. Also, make sure to close the connection once your App is unmounted

function App() {
  const [socket, setSocket] = useState(null);

  useEffect(() => {
    const s = io("http://localhost:3000/");
    setSocket(s);

    return () => s.disconnect();
  }, [setSocket]);

  return (
    <div className="App">
      <Home />
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!