skip to Main Content

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();
    };
  }, []);

2

Answers


  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.

    Login or Signup to reply.
  2. 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();
        };
      }, []);
    }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search