0

my usesate why rendering two times? enter image description here

I used [] at the end of the usestate so it should render once but it fetching data two times which gives me a duplicate render.

useEffect(() => {
    const socket = io("http://localhost:3001");
    let public_key;
    if (roomID.length == 0) {
      axios
        .post(
          `${domain}/chat/publickey?is_update_key=false`,
          {},
          { withCredentials: true }
        )
        .then((res) => {
          console.log(res);
          public_key = res.data.detail;
          console.log(public_key);
          socket.emit("admin_room", public_key, socket.id);
          axios
            .get(`${domain}/chat/admin/${public_key}?page=1&items_per_page=5`, {
              withCredentials: true,
            })
            .then((res) => {
              setRoomID((prev) => [...prev, res.data]);
            });
        })
        .catch((err) => {
          console.log(err);
        });
    }

    socket.on("customer_message", (data) => {...my othessocket io code
      return () => {
      socket.disconnect();
    };
  }, []);
boyenec
  • 1,405
  • 5
  • 29

2 Answers2

0

You are calling setRoomID() twice in the useEffect hook.

 const [roomID, setRoomID] = useState([]);

useEffect(() => {
  const socket = io("http://localhost:3001");
  let public_key;
  if (roomID.length == 0) {
    axios
      .post(
        `${domain}/chat/publickey?is_update_key=false`,
        {},
        { withCredentials: true }
      )
      .then((res) => {
        console.log(res);
        public_key = res.data.detail;
        console.log(public_key);
        socket.emit("admin_room", public_key, socket.id);
        setRoomID([public_key]);
      })
      .catch((err) => {
        console.log(err);
      });
  }

  socket.on("customer_message", (data) => {...my othessocket io code
    return () => {
      socket.disconnect();
    };
  }, []);
}, []);
I_Al-thamary
  • 3,385
  • 2
  • 24
  • 37
-1

if you have StrictMode turned on, it will run useEffect twice. You can turn off StrictMode but I think the proper solution is to get rid of side effects instead of turning off StrictMode. But in production build, it will not render twice. It is only a dev thing to help remove unexpected side-effects. In you app.js if you have something like this:

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

Remove the StrictMode wrapper. But again, the proper thing to do is solve the issue, not remove StrictMode. Hope this helps.

SSubedi
  • 79
  • 1
  • 11
  • I am not using StrictMode anywhere – boyenec Jul 17 '23 at 16:25
  • if it is not due to strict mode, then there is some side effect going on causing your component to re-render. UseEffect() is being ran once per render, but some state change maybe causing double render... look at setRoomID().. that is the only state change i see in the code you gave... – SSubedi Jul 17 '23 at 16:36