title: live chat app using socket.io and ReactJS
body: <p>I am building a live chat app using ReactJS and socket.io. I am almost done with the app but stuck at user disconnection. When an user left the room a disconnect message is emitting 4 times as you can see in below picture.</p>
  <p> <a href="https://i.stack.imgur.com/4dTga.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4dTga.png" alt="enter image description here" /></a></p>
  <p>This is my client side code (Not the whole code)</p>
  <pre><code>const ChatRoom = ({ location }) =&gt; {
      const { userName, setUserName } = useContext(ChatContext)
      const { roomCode, setRoomCode } = useContext(ChatContext)
      const [message, setMessage] = useState('')
      const [chats, setChats] = useState([])
      const ENDPOINT = 'localhost:5000'
      const socket = io(ENDPOINT)
      
      useEffect(() =&gt; {
          const { userName, roomCode } = queryString.parse(location.search)
          
          setUserName(userName)
          setRoomCode(roomCode)
  
          socket.emit('chatroom-join', {userName, roomCode})
  
          return () =&gt; {
              socket.emit('disconnect', {userName})
              socket.off()
          }
      }, [location.search, ENDPOINT])
  
   useEffect(() =&gt; {
          socket.on('message', ({userName, message}) =&gt; {
              setChats(chats =&gt; [...chats, {userName, message}])
          })
      }, [])
  </code></pre>
  <p>My Server side code</p>
  <pre><code>// Socket.io API
  io.on('connection', (socket) =&gt; {
      socket.on('chatroom-join', ({userName, roomCode}) =&gt; {
          console.log('User joined')
          socket.join({roomCode})
          io.to({roomCode}).emit('message', {userName: 'admin', message: `${userName} has joined`})
      })
      
      socket.on('message', ({userName, message}) =&gt; {
          io.emit('message', {userName, message})
      })
  
      socket.on('disconnect', () =&gt; {
          io.emit('message', {userName: 'admin', message: 'An user has left'})
          console.log('User disconnected')
          socket.disconnect(true)
      })
  })
  </code></pre>