skip to Main Content

When I try to refresh page it prints "1" twice.

But I’m not using any useState or variable update or state change I think.

Can you tell me where I’m wrong?

import "./styles.css";
import React, { useState, useEffect, useRef } from "react";
//import { io } from "socket.io-client";
//const socket = io("ws://localhost:4000");

export default function App() {
  const newUser = () => {
    //socket.emit("newUser", { socketID: socket.id });
  };

  const checkUser = () => {
    //socket.emit("checkUser", { socketID: socket.id });
  };

  const resetUser = () => {
    //socket.emit("resetUser", { socketID: socket.id });
  };

  const checkSocket = () => {
    //console.log(socket);
  };

  const disconnectSocket = () => {
    //socket.emit("disconnect");
  };

  useEffect(() => {
    console.log("1");
  }, []);

  /*useEffect(() => {
    console.log("2", socket);
    //if(socket.id) socket.emit("newUser", {socketID: socket.id});
    //socket.on("checkUser", data => console.log("check", data));
    //socket.on("newUserResponse", data => console.log("newUserResponse", data));
    return () => {
    };
  }, [socket]);
  */

  return (
    <div className="App">
      <div>
        <button onClick={newUser}>New User</button>
      </div>
      <div>
        <button onClick={checkUser}>Check User</button>
      </div>
      <div>
        <button onClick={resetUser}>Reset User</button>
      </div>
      <div>
        <button onClick={checkSocket}>Check Socket</button>
      </div>
      <div>
        <button onClick={disconnectSocket}>Disconnect Socket</button>
      </div>
    </div>
  );
}

2

Answers


  1. Maybe you’ve got two render cause you’ve keep the Strict Mode

    Login or Signup to reply.
  2. This is something introduced in React 18 where the component loads twice in strict mode. This only happens in development mode and NOT in production.

    For more information see : https://legacy.reactjs.org/docs/strict-mode.html#ensuring-reusable-state

    From the Docs :
    enter image description here
    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search