Home > Enterprise >  React creates a lot of new connection with Socket.io
React creates a lot of new connection with Socket.io

Time:01-20

The main problem that I have, is that React is creating sockets connections, but I don't understand why.

I tried to recreate it with a minimal code example:

Code

import { useState, useEffect, useCallback } from 'react';
import io from 'socket.io-client';

// Main
const Test = () => {
    // Hooks
    const [buttons, setButtons] = useState(null);
    const [isConnected, setIsConnected] = useState(false);
    const socket = io();

    useEffect(() => {

        // Connection
        socket.on('connect', () => {
            console.log("  Connected")
            setIsConnected(true);
        });

        // Disconnection
        socket.on('disconnect', () => {
            setIsConnected(false);
        });

        // Turning off socket
        return () => {
            socket.off('connect');
            socket.off('disconnect');
            socket.disconnect();
        };
    }, []);


    window.addEventListener("mousemove", (e) => {
        console.log(e.buttons)
        setButtons(() => e.buttons)
    });

    return (
        <>
            <span>Connected: {"" isConnected}</span><br/>
            <span>Buttons: {buttons}</span>
        </>
    );
}

export default Test;

This code is a basic code example, that add an adventListener for "mousemove" on the window, and set buttons to the buttons pressed.

When you quickly alternate between moving the mouse on the page and resizing the page, at some point it will create a hundred connections with the server:

Server side history of connections

But, the client doesn't log Connected.
This huge increase of connection makes everything slow and overloads the client and server.

I tried to use the hook useCallBack and to put the eventListener in a useEffect, but didn't change anything, and I didn't find anybody with the same problem.

I would like to know, why so many connections are created, and how to prevent this from happening.

More info

The back-end is in Node.JS

CodePudding user response:

Try to define your socket above your Test component, directly after the imports. Also i remember passing the server URL and executing the connect method right on initialization when i did a React NodeJS project.

import { useState, useEffect, useCallback } from 'react';
import io from 'socket.io-client';

const socket = io.connect(PASS_SERVER_IP_HERE);

// Main
const Test = () => {
    // Hooks
    const [buttons, setButtons] = useState(null);
    const [isConnected, setIsConnected] = useState(false);


[...]
  • Related