How to Implement WebSockets in React Native - LogRocket Blog (2023)

The web was originally implemented on the principle of request and response: a client sends a request and a server responds with the appropriate response. When there is no requirement to handle data according to a client request, it is common to display a static page.

whendynamic pagescame, we were introduced to the concept of GET, POST, PUT and DELETE requests. Now a client can request custom data from a server by sending its requests as parameters. The server then processes the request and returns a dynamic response.

However, the basics are based on request and response: the client asks, the server responds, and the connection is closed.

There is another protocol that does not work as a request-response scheme known as WebSockets. In this tutorial, we will introduce you to WebSockets technology and some common use cases. We'll show you how to implement WebSockets in React Native by designing a messaging app.

What are WebSockets?

WebSockets is a protocol that caresfull-duplexcommunication, meaning that the client and server remain connected over a single TCP connection. Unlike request-response communication, the connection is not interrupted here.

Since it is full-duplex, the server can also send data to the client without a request. This helps save bandwidth and response time.

The WebSockets protocol starts withws://. To handle the hypertext we usehttp://ofhttps://.

Why use WebSockets?

There are various uses for WebSockets, but we mainly use them in situations where data needs to be transmitted or forwarded from the server.

For example, a chat application server must send a message to a recipient as soon as the sender sends it. The server cannot wait for the client to request new messages, so it pushes them to the client using full-duplex communication. Likewise, news, trade board and even social media posts are promoted this way.

This effect could be achieved before WebSockets appeared, but they were unreliable and inefficient.

For example, many companies used long polling where a browser sends a request but the server does not respond. The connection remains active until a connection timeout occurs. Meanwhile, if the server has a message for the client, it will reply and disconnect. Once the connection is lost, either due to a timeout or a response from the server, the client resends the request. This process goes on and on.

Another approach is to send an AJAX request every few seconds, say three seconds, and get a response from the server, which is either a valid message or an empty object. So a new message can be delayed up to three seconds. The downside of this approach is that many API calls are lost because the server has no message to respond to.

Using WebSockets in React Native

There are four main operations performed during the WebSockets lifecycle. They are called when the application establishes a connection, receives a message, detects an error, and disconnects.

Let's zoom in on these features.

Create a WebSockets connection

The first step is to establish a connection to the server. WebSockets operate according to their own protocol,ws://.

In React Native, we can create a connection using the following code:

var ws = new WebSocket('ws://');

Here the link corresponds tohost service running on the backend.

If the server accepts the connection, it notifies the client by sendingopenfunction on the WebSocket object:

ws.onopen = () => { // open connection ws.send('something'); // send a message };

This works as a constructor. You can allocate resources to this function. Also, if you need to send one-time use information to the server, such as a user identification number, you can do so here.

Over 200,000 developers use LogRocket to build better digital experiences Learn more →

Receive messages

In a request-response policy, the client looks for a response to the sent request. This means that the client knows when it will receive data from the server, so it remains ready to process it. But with full two-way communications like WebSockets, the server can send data at any time without the client's permission.

To handle this situation, a function must be called when the server sends a message.

In React Native we have onemessagefunction for this:

ws.onmessage = (e) => { // received a message console.log(; };

Handling errors

When an error occurs, either due to a bad internet connection or internal server errors, theerrorthe function is called:

ws.onerror = (e) => { // an error occurred console.log(e.message); };

Close the connection

When the connection is dropped, either by the server or the client, thelock upthe function is called. This acts as a destructor as you can release the allocated resources.

ws.onclose = (e) => { // closed connection console.log(e.code, e.reason); };

We have now seen the complete lifecycle of WebSockets in React Native from creating a connection to closing it. We can write all these functions in a block like this:

var ws = new WebSocket('ws://'); ws.onopen = () => { // open connection ws.send('something'); // send message};ws.onmessage = (e) => { // received a message console.log(;};ws.onerror = (e) => { // a message was an error occurred console .log(e.message);};ws.onclose = (e) => { // connection closed console.log(e.code, e.reason);};

WebSockets Example: Messaging application

To show WebSockets in action, let's create a simple messaging application in Rect Native. In our demo application, a message sent by one application is broadcast to all connected applications.

Gooddeploy the server script in Node.js. This is the WebSockets server code:

const express = vereisen("express"); const app = express(); const http = vereisen("http"); const WebSocket = vereisen("ws"); const server = http.createServer(app); const wss = nieuwe WebSocket.Server({ server });wss.on("connection", function connection(ws) { ws.on("message", function incoming(message, isBinary) { console.log(message.toString(), isBinary); wss.clients.forEach(function each(client) {if (client.readyState === WebSocket.OPEN) {client.send(message.toString()); } }); });});app .get("/", (req, res) => { res.send("Hello World!");}); server.listen(8080, () => { console.log("Luisteren naar port 8080" );});

You can find this code in the npm repository for thews package.

Remember to keep the server running. Otherwise, clients cannot connect.

Customer's code

Now that our server is up and running successfully, it's time to build our React Native app.

At the top we create a horizontal bar to display login or disconnection notifications and errors. At the bottom we place an input field and a send button for sending messages via WebSockets. The rest of the middle area is used to display the list of messages received from the server.

More great articles from LogRocket:

  • Don't miss a moment withThe repetition, a curated newsletter from LogRocket
  • To learnhow LogRocket's Galileo reduces noise to proactively fix problems in your application
  • Use React's useEffectto optimize the performance of your application
  • Switch betweenmultiple versions of Node
  • Learn how to animateyour React app with AnimXYZ
  • No paths either, a new framework for creating binaries
  • Advisory boards aren't just for managers.Join LogRocket's Content Advisory Board.You help inform us about the kind of content we create and gain access to exclusive meetings, social recognition and swag.

It's a broadcast app, so any message sent from any device will be broadcast to everyone.

Let's take a look at the code:

εισαγωγή * ως React from 'react';import { Text, View, StyleSheet, TextInput, Button, ScrollView } from 'react-native';export default function App() { const [serverState, setServerState] = React.useState('Loading ...'); const [messageText, setMessageText] = React.useState(''); const [disableButton, setDisableButton] = React.useState(true); const [inputFieldLeeg, setInputFieldLeeg] = React.useState(true); const [serverBerichten, setServerBerichten] = React.useState([]); var ws = React.useRef(nieuwe WebSocket('ws://')).huidig; React.useEffect(() => { const serverMessagesList = []; ws.onopen = () => { setServerState('Verbonden met de server') setDisableButton(false); }; ws.onclose = (e) => { setServerState('Niet verbonden. Controleer Internet of server.') setDisableButton(true); }; ws.onerror = (e) => {setServerState(e.message); }; ws.onmessage = (e) => {serverMessagesList push(;setServerMessages([...serverMessagesList]) };}, []) const submitMessage = () => { ws.send(messageText); setMessageText('') setInputFieldEmpty(true) } return (  {serverState }   {, ind) => { return ({kind}) }) }   { setMessageText(text) setInputFieldEmpty(text.length > 0 ? false : true)} } value={messageText} />  );}const styles = StyleSheet.create( { container: { flex: 1, backgroundColor: '#ecf0f1', paddingTop: 30, padding: 8, },});

To summarize briefly, the process for implementing WebSockets in a React Native application is as follows:

  1. The React Native app creates a new WebSockets connection and stores it in a reference variable,ws
  2. The top line of the app shows its valueserver statusvariable, the middle part represents a text message stored inserver reportstable and the bottom line has an input field that stores typed messages inmessage textstate variable
  3. The submit button will not fire until the application has successfully connected to WebSockets and there is some text in the input box. We check it using itpower off buttonIninputFieldEmptyvariables. The submit button is active when bothpower off buttonIninputFieldEmptyIsvalves
  4. In theuseEffect()hook , we define all the WebSocket functions
  5. When the WebSockets connection is opened by the server, theopenthe function is called. This changes its valueserver statusvariable toconnected to the serverInpower off buttonUnpleasantvalves, so the top bar of the app shows the linked message
  6. When the connection is lost, thelock upthe function is called. This changes itserver statusUnpleasantdisconnected messageInpower off buttonUnpleasantWHERE. Currently the send button is no longer active even if you type a message in the input box because we can't send messages to the server
  7. If there is an error, theerrorthe function is called and changes theserver statusin the specific error message
  8. When the server broadcasts messages, themessagethe function is called. Adds the received message toserver reportssmell
  9. We made oneto send a messagemessage to send the message to the server, which the server broadcasts to all devices

Here I have embedded two copies of this app: one for Android and another for iOS. You can check if the message sent from one device is displayed on both. Check that the Node.js server we embedded above is working properly and not in a sleep state.

If you are having problems with the above devices, please run the codehere.


In this tutorial, we showed you how easy it is to create WebSockets in React Native apps. The code works on both Android and iOS platforms.

We've created a simple broadcast app for this demo, but there's plenty of room for expansion. For example, you can set identifiers to distinguish between clients and align messages sent by the client to the right and everything else to the left. This creates a perfect chat app like look and feel.

You can also create a form to capture details (such as username) before starting a chat and display the information next to received messages.

Let us know in the comments what kind of stuff you've built in React Native using WebSockets.

LogRocket: Create instant problems in your React Native apps.

LogRocketis a React Native monitoring solution that allows you to instantly reproduce issues, prioritize bugs, and understand the performance of your React Native apps.

LogRocket also helps you increase conversion rates and product usage by showing you exactly how users interact with your app. LogRocket's product analytics capabilities reveal why users don't complete a certain flow or use a new feature.

Start proactively monitoring your React Native apps —try LogRocket for free.


Can you use WebSockets in react native? ›

React Native also supports WebSockets, a protocol which provides full-duplex communication channels over a single TCP connection.

How do you implement a WebSocket in react native? ›

Creating a WebSockets connection

In React Native, we can create a connection using the following code: var ws = new WebSocket('ws://'); Here the link corresponds to the socket service running on the backend.

How do I connect to a WebSocket in react? ›

We connect the WebSocket server to the HTTP port when it's been created: const webSocketServer = require('websocket'). server; const http = require('http'); const webSocketServerPort = 8000; // Start the http server and the websocket server const server = http.

How to generate WebSocket URL? ›

To open a websocket connection, we need to create new WebSocket using the special protocol ws in the url: let socket = new WebSocket("ws://"); There's also encrypted wss:// protocol. It's like HTTPS for websockets.

What is the best WebSocket library for React Native? ›

A good library for providing robust WebSocket integrations in React is called react-use-websocket. This library provides a custom React hook for implementing WebSocket integrations and it has experimental support for SocketIO.

When should you not use WebSockets? ›

You might be using WebSockets incorrectly if:
  1. The connection is used only for a very small number of events, or a very small amount of time, and the client does not need to quickly react to the events.
  2. Your feature requires multiple WebSockets to be open to the same service at once.
Mar 14, 2016

How do you deploy a WebSocket? ›

First, open a terminal window and create a new project directory and then navigate to the new directory.
  1. $ mkdir sample-websocket $ cd sample-websocket. At this point, you can initialize a new npm project. ...
  2. $ npm init -y. Next, install the express and ws packages. ...
  3. $ npm install express ws.
Aug 11, 2022

How to connect WebSocket to API? ›

Invoking a WebSocket API
  1. You can use wscat to connect to your WebSocket API and send messages to it to simulate client behavior. ...
  2. You can use the @connections API from your backend service to send a callback message to a connected client, get connection information, or disconnect the client.

How many connections can WebSockets handle? ›

In theory, a server can handle up to 65,536 sockets per single IP address. In practice, though, there are many factors that influence how many WebSocket connections can be handled by a server: hardware resources, network bandwidth, size and frequency of messages that are transmitted over the WebSocket connections, etc.

How do I enable WebSocket connection? ›

- In Control Panel, click Programs and Features, and then click Turn Windows features on or off. Expand Internet Information Services, expand World Wide Web Services, expand Application Development Features, and then select WebSocket Protocol. Click OK. Click Close.

How to install WebSocket server? ›

See the godoc page for additional information.
  1. Update config.yml.
  2. Update nginx configuration.
  3. Install arvados-ws package.
  4. Start the service.
  5. Restart the API server and controller.
  6. Confirm working installation.

Why can't i connect to WebSocket? ›

Try the following to troubleshoot the issue.
  • Proxy rules. Create a custom WebSocket header. ...
  • HTTPS connection. Sign in to Surveillance Station via HTTPS.
  • Antivirus program. Check if your antivirus program has blocked the connection from your computer to Surveillance Station. ...
  • Video relay service. ...
  • Contact support.
Jul 11, 2022

What is the URL for WebSockets? ›

Enter the WebSocket server URL. A WebSocket URL begins with ws:// or wss:// . Select Connect.

How to create WebSocket endpoint? ›

  1. Click File > New > Other. Under the Web category, select WebSocket Endpoint.
  2. Right-click a selected project. Select New > WebSocket Endpoint.

What HTTP method does WebSocket use? ›

Web Socket Connections

Web sockets use the HTTP transmitting mechanism to initiate a request from the client. Once the request from the client reaches the server, they may use the TCP connection as a web socket connection where sending multiple information requests is possible.

What is a good backend for React Native? ›

Supabase and Firebase are two of the most famous backend as a service (BaaS) products. Firebase, now owned by Google, provides the tools for developers to build and ship their applications on the web and mobile.

How much faster is WebSocket than HTTP? ›

Here we can see that the HTTP benchmark peaks at about~950 requests per second while serves about ~3900 requests per second.

What is faster than WebSockets? ›

WebRTC primarily works over UDP, while WebSocket is over TCP. This means that WebRTC offers slightly lower latency than WebSockets, as UDP is faster than TCP. However, the difference is negligible; plus, TCP is more reliable when it comes to packet delivery (in comparison, with UDP some packets may be lost).

What is the disadvantage of using WebSocket? ›

The biggest downside to using WebSocket is the weight of the protocol and the hardware requirements that it brings with it. WebSocket requires a TCP implementation, which may or may not be a problem, but it also requires an HTTP implementation for the initial connection setup.

What are the weaknesses of WebSocket? ›

Drawbacks or disadvantages of Websockets

Intermediary/Edge caching is not possible with websockets unlike HTTP. ➨To build even simple protocol of your own, one can not be able to use friendly HTTP statuses, body etc. ➨If application does not require a lot of dynamic interaction, HTTP is much simpler to implement.

What is the disadvantage of WebSockets? ›

Cons of Websocket
  • A fully HTML5-compliant web browser is required.
  • AJAX-like success mechanisms are not available in Websockets.
  • Websockets, unlike HTTP, do not provide intermediary/edge caching.
  • It is impossible to employ friendly HTTP statuses, bodies, and other elements to create even a simple protocol of your own.
Oct 15, 2021

How to pass data to WebSocket? ›

WebSocket: send() method. The WebSocket. send() method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of bufferedAmount by the number of bytes needed to contain the data.

What is the difference between WebSocket and socket IO? ›

Socket.IO vs WebSocket: what are the differences? WebSocket is a technology that enables two-way realtime communication between client and server. In contrast, Socket.IO is a library that provides an abstraction layer on top of WebSockets, making it easier to create realtime applications.

How do I get data from a WebSocket? ›

First, you need to copy your web browser's header to here and use json. dumps to convert it into the string format. After that, create the connection to the server by using create_connection . Then, perform the handshake by sending the message, and you will be able to see the data on your side.

Can a REST API use WebSockets? ›

REST requires a stateless protocol according to the statelessness constraint, websockets is a stateful protocol, so it is not possible.

How do I know if my WSS is working? ›

Inspect the client-side source code for the ws:// or wss:// URI scheme.
  1. Use Google Chrome's Developer Tools to view the Network WebSocket communication.
  2. Use ZAP's WebSocket tab.

What is the difference between API gateway REST and WebSocket? ›

The WebSocket API invokes your backend based on the content of the messages it receives from client apps. Unlike a REST API, which receives and responds to requests, a WebSocket API supports two-way communication between client apps and your backend. The backend can send callback messages to connected clients.

Why WebSockets are not scalable? ›

But why are WebSockets hard to scale? The main challenge is that connections to your WebSocket server need to be persistent. And even once you've scaled out your server nodes both vertically and horizontally, you also need to provide a solution for sharing data between the nodes.

Can two clients connect to the same WebSocket? ›

A server can open WebSocket connections with multiple clients—even multiple connections with the same client. It can then message one, some, or all of these clients. Practically, this means multiple people can connect to our chat app, and we can message some of them at a time.

How much RAM does a WebSocket use? ›

The exact use of memory for websocket(not ) is: for 1 TCP connection it take 40MB, for 1000(1k) TCP connections it take 80 MB, for 10,000(10k) TCP connections it takes 210 MB.

How do I know if my WebSocket is connected? ›

You can check if a WebSocket is connected by doing either of the following:
  1. Specifying a function to the WebSocket. onopen event handler property, or;
  2. Using addEventListener to listen to the open event.
Sep 27, 2021

What port does WebSocket use? ›

TCP: Typically, WebSocket uses TCP as its transport protocol. The well known TCP port for WebSocket traffic is 80 and 443.

Do WebSockets close automatically? ›

However, the connection between a client and your WebSocket app closes when no traffic is sent between them for 60 seconds.

How to install simple WebSocket server? ›

  1. Installation. pip install simple-websocket-server.
  2. Echo Server Example. from simple_websocket_server import WebSocketServer, WebSocket class SimpleEcho(WebSocket): def handle(self): # echo message back to client self. ...
  3. Chat Server Example. ...
  4. Want to get up and running faster? ...
  5. TLS/SSL Example. ...
  6. For the Programmers.

Is WebSocket supported by your browser? ›

Web Sockets on Android Browser is fully supported on 4.4-111, partially supported on None of the versions, and not supported on 2.1-4 Android Browser versions. Web Sockets on Opera Mobile is fully supported on 12.1-73, partially supported on 11.5-12, and not supported on 10-10 Opera Mobile versions.

How do I enable WebSocket on App Service? ›

Developers can enable and use WebSockets in their applications by turning on WebSockets feature in App Service Configuration -> General Settings portal.
Deploy to Linux App Service
  1. Create a Linux App Service, or using an existing Linux App Service. ...
  2. Run the Maven command below to configure the deployment.
Feb 20, 2022

How to start a WebSocket server? ›

In Postman, select New > WebSocket Request to open a new tab. Enter the WebSocket server URL. A WebSocket URL begins with ws:// or wss:// and our server is running on localhost:8080 . Click Connect.

Can WebSocket be on any port? ›

WebSocket connections generally work even if a proxy or firewall is in place. This is because they use ports 80 and 443 which are also used by HTTP connections. In some situations WebSocket connections are blocked over port 80. In this case a secure SSL connection using WSS over port 443 should successfully connect.

Why are WebSockets obsolete? ›

Websockets are largely obsolete because nowadays, if you create a HTTP/2 fetch request, any existing keepalive connection to that server is used, so the overhead that pre-HTTP/2 XHR connections needed is lost and with it the advantage of Websockets.

Is WebSocket over HTTP or HTTPS? ›

WebSocket is distinct from HTTP. Both protocols are located at layer 7 in the OSI model and depend on TCP at layer 4. Although they are different, RFC 6455 states that WebSocket "is designed to work over HTTP ports 443 and 80 as well as to support HTTP proxies and intermediaries", thus making it compatible with HTTP.

Does WebSocket use HTTP or HTTPS? ›

The WebSocket protocol uses HTTP transmitting mechanisms and starts as standard HTTP requests and responses. Inside of this communication chain, the client requests to open a WebSocket connection. If the request is successful, the client and the server start using the TCP connection as a WebSocket connection.

What are some examples where Websockets are used? ›

WebSocket is useful when fast connections are important. Examples include live chats on support websites, news tickers, stock tickers, messaging apps, and real-time games.

What is the endpoint of a WebSocket? ›

The Web Socket Endpoint represents an object that can handle websocket conversations. Developers may extend this class in order to implement a programmatic websocket endpoint. The Endpoint class holds lifecycle methods that may be overridden to intercept websocket open, error and close events.

What is handshake in WebSocket? ›

WebSockets - Overview

In computer science, handshaking is a process that ensures the server is in sync with its clients. Handshaking is the basic concept of Web Socket protocol. The following diagram shows the server handshake with various clients −

Does react support WebSocket? ›

Creating a handshake request at the client level

react-use-websocket offers the useWebSocket hook to manage WebSocket connections from React functional components. Check the react-use-websocket documentation to become more familiar with the particular React hook's design.

Can you use Socket.IO with React Native? ›

Now that we have the server set up, we can begin integrating the React Native application with the Socket.IO server. To do this, open the App. js file in your text editor and add the following code: const socket = SocketIOClient('http://localhost:3000'); socket.

Can I make a web app with React Native? ›

Can React Native be used for web and mobile? Yes certainly, React Native, which is a cross-platform app development framework, can also be used to develop web applications.

What language works best with WebSockets? ›

A WebSocket server can be written in any server-side programming language that is capable of Berkeley sockets, such as C(++), Python, PHP, or server-side JavaScript.

Where do I deploy WebSocket? ›

First, open a terminal window and create a new project directory and then navigate to the new directory.
  • $ mkdir sample-websocket $ cd sample-websocket. At this point, you can initialize a new npm project. ...
  • $ npm init -y. Next, install the express and ws packages. ...
  • $ npm install express ws.
Aug 11, 2022

What will replace WebSocket? ›

While WebSockets can be used for various applications, MQTT is explicitly designed for machine-to-machine communication, which is why it's considered an alternative under these use cases. MQTT provides features like low overhead, efficient message delivery, and support for offline operation.

How do I enable WebSocket support? ›

- In Control Panel, click Programs and Features, and then click Turn Windows features on or off. Expand Internet Information Services, expand World Wide Web Services, expand Application Development Features, and then select WebSocket Protocol. Click OK. Click Close.

What is alternative of Socket.IO for React Native? ›

SignalR, SocketCluster, PubNub, Pusher, and ExpressJS are the most popular alternatives and competitors to Socket.IO.

How to install Socket.IO in React Native? ›

Then, create the project folder and an Expo React Native app by running the code below.
  1. mkdir chat-app cd chat-app expo init app. ...
  2. ? ...
  3. cd app expo install ...
  4. mkdir utils touch socket.js //👇🏻 Paste within socket.js file. ...
  5. import { io } from "socket.
Oct 17, 2022

Can we use node with React Native? ›

You will need Node, the React Native command line interface, a JDK, and Android Studio. While you can use any editor of your choice to develop your app, you will need to install Android Studio in order to set up the necessary tooling to build your React Native app for Android.

Is React Native web a good idea? ›

React Native for Web is a good option for those who are starting with a native app, and want to turn that native app into a web app very quickly. It's also a good option if the web app and the natvie app are to be very similar: in other words, the web app should do everything the native app does, and no more.

Does Facebook use React Native? ›

Facebook's Departure from React Native: An Opportunity to Explore New Frameworks. Facebook, the social media giant, recently announced its decision to pull out of React Native, the open-source JavaScript framework that was developed and maintained by Facebook.

Is React Native enough to build an app? ›

As an established “hybrid” framework for mobile app development, React Native is proven efficient at cross-platform duties, attractive, popular among devs, and saves time and money.

What is the downside of WebSockets? ›

Cons of Websocket
  • A fully HTML5-compliant web browser is required.
  • AJAX-like success mechanisms are not available in Websockets.
  • Websockets, unlike HTTP, do not provide intermediary/edge caching.
  • It is impossible to employ friendly HTTP statuses, bodies, and other elements to create even a simple protocol of your own.
Oct 15, 2021

Is WebSocket better than REST API? ›

WebSockets have a low overhead per message. They're ideal for use cases that require low-latency, high-frequency communication. REST APIs have a higher message overhead compared to WebSockets. They're best suited for use cases where you want to create, retrieve, delete, or update resources.

What is the fastest language for WebSockets? ›

In this benchmark there is one clear winner: uWebSockets-library. uWebSockets, which is written in C/C++, was the fastest performing WebSocket server both when used with Node. js and Python. The speed is impressive but so is the resource usage.


Top Articles
Latest Posts
Article information

Author: Roderick King

Last Updated: 04/11/2023

Views: 6231

Rating: 4 / 5 (51 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Roderick King

Birthday: 1997-10-09

Address: 3782 Madge Knoll, East Dudley, MA 63913

Phone: +2521695290067

Job: Customer Sales Coordinator

Hobby: Gunsmithing, Embroidery, Parkour, Kitesurfing, Rock climbing, Sand art, Beekeeping

Introduction: My name is Roderick King, I am a cute, splendid, excited, perfect, gentle, funny, vivacious person who loves writing and wants to share my knowledge and understanding with you.