my usesate why rendering two times?
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
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:
Remove the StrictMode wrapper. But again, the proper thing to do is solve the issue, not remove StrictMode. Hope this helps.
You are calling setRoomID() twice in the
useEffect
hook.