DEV Community

Sumrit Grover
Sumrit Grover

Posted on

React Native Chat App using Socket.io

React Native with Socket.io

Let's create a basic chat app using React Native as your frontend and socket as your backend

Socket IO

The formal definition is that socket enables real-time, bidirectional event-based communication between the client and the server. It consists of a Node.js server and JS Client

This basically means is that data is transported between server and client in realtime.

Basic Socket Event Handlers

  • item 1 On - on() listens for a ‘connection’ event and will run the provided function anytime this happens.

io.on("connection", (socket) => {});

  • item 2 Emit - emit() to send a message to all the connected clients io.emit("message", {message,sid,time,rid});

Server Code with Socket

The server code is written on a node server using HTTP and express

Image description

Client side code with React Native

Using socket.io-client connect the client to the server. The useRef hook is essential to reference the socket.

Image description

Top comments (4)

Collapse
 
sebduta profile image
Sebastian Duta • Edited

This saved me so much time, thank you! For more advanced features, I usually use this React Native Chat app to save months of development

Collapse
 
cdehaan profile image
Chris DeHaan

Fantastic, this was instrumental in getting socket.io to work in React for me. Thanks

Collapse
 
mansa62 profile image
Mansa

Does the IP have to be private or can a public IP be used?

Collapse
 
sumonsbgc profile image
Mohammad Sumon • Edited

If I disconnect socket on componentWillUnMount in useEffect, How Can I communicate with other Clients when their app is in close totally?