Telerik blogs

WebSocket is a protocol for creating two-way communication between a client and a server. See how it eases the process of sending and receiving data in real-time React apps.

Technology changed our lives for the better. We can say that one of the good reasons for that is because of real-time communication. It has transformed our world, enabling us to exchange information with whomever whenever we want to. A whole set of new businesses were created due to the invention of real-time communication.

Real-time communication is everywhere. Every time we are using a chat or video conference app, for example. It makes the communication feel like real life, as if the person was sitting next to us in the same room.

It has also become a vital part of some modern apps. Users want to be able to communicate with other users in real-time, without having to worry about sending a response or waiting for a response. For real-time communication to happen, the users must be able to be perfectly synchronized.

WebSocket has pretty much everything to do with real-time communication and the way we’re developing real-time apps. It is a very powerful technology that enables us to develop applications that can have real-time features.

Let’s understand more about WebSockets and how they work.

How WebSocket Works

WebSocket is a protocol that supports full-duplex or two-way communication between a client (e.g., a browser) and a server. It provides full-duplex communication channels over a single TCP connection.

WebSockets are a better solution over HTTP request/response connections because they can deliver an unlimited amount of data without the need for polling.

Websockets diagram shows client on one side and server on the other. Mutual handshake, mutual websocket, then either side can close.

The connection between client and server lasts until any of the participating parties lays it off. Once one side breaks the connection, the second one won’t be able to communicate, as the connection breaks automatically.

WebSockets in React Apps

Before we start with this example, I’d like to point out that there’s not a standard way of using WebSocket in React applications. Every developer can implement it using different ways, but at the end of the day, we want to accomplish a reliable, structured and easy way of doing so.

One of the best ways of implementing WebSockets in React is by using a library. We want to remove the friction and go straight to the implementation. Most of the time, you don’t want to spend hours or maybe days of work creating your own library for that.

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.

We can get started by installing it:

yarn add react-use-websocket

This library provides a hook called useWebSocket. We’re going to use this hook for integrating our React code with a socket. It receives three parameters: a URL string, an options object and a shouldConnect value that tells if we should or not reconnect to the socket.

import useWebSocket from 'react-use-websocket';

const {
  sendMessage,
  sendJsonMessage,
  lastMessage,
  lastJsonMessage,
  readyState,
  getWebSocket,
} = useWebSocket('wss://echo.websocket.org', {
  onOpen: () => console.log('opened'),
  shouldReconnect: (closeEvent) => true,
});

Once a socket is created, we should listen to events on it. A socket has four possible events:

  • open – connection established
  • message – data received
  • error – WebSocket error
  • close – connection closed

The second parameter on the useWebSocket hook is very important because we can implement what we want in these four possible events. Let’s imagine that we wanted to perform some state change after our socket is open:

import useWebSocket from 'react-use-websocket';

const {
  sendMessage,
  sendJsonMessage,
  lastMessage,
  lastJsonMessage,
  readyState,
  getWebSocket,
} = useWebSocket('wss://echo.websocket.org', {
  onOpen: () => {
    setIsOpen(true);
    setIsLoading(true);
    ...
  },
  shouldReconnect: (closeEvent) => true,
});

The hook also supports async URLs. Instead of passing a string as the first argument to useWebSocket, you can pass a function that returns a string (or a promise that resolves to a string).

import useWebSocket from 'react-use-websocket';

const getSocketUrl = useCallback(() => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('wss://echo.websocket.org');
    }, 2000);
  });
}, []);

const {
  sendMessage,
  sendJsonMessage,
  lastMessage,
  lastJsonMessage,
  readyState,
  getWebSocket,
} = useWebSocket(getSocketUrl, {
  onOpen: () => {
    setIsOpen(true);
    setIsLoading(true);
    ...
  },
  shouldReconnect: (closeEvent) => true,
});

The reason to use a third-party library for handling WebSocket integration in React is because it can become really complex and hard to manage your own implementation. There are many corner cases that need to be covered, and most of the time we don’t have capacity for implementing our own solution for that.

In case you don’t want to install another library on your project, you can try to create your own custom React hook. It can be something like this:

import * as React from 'react';

const useWebSockets = () => {
  React.useEffect(() => {
    const websocket = new WebSocket('wss://echo.websocket.org/');

    websocket.onopen = () => {
      console.log('connected');
    }

    websocket.onmessage = (event) => {
      const data = JSON.parse(event.data);
    }
  
    return () => {
      websocket.close()
    }
  }, [])
}

When To Use WebSocket?

WebSocket is a client-server communication protocol that can be powerful if used in the right situations. Most of the time, the primary reason to use WebSocket is when you want to develop a real-time application.

As the server sends data back continuously, WebSocket allows uninterrupted communication between client and server. It means that sending or receiving data in an open connection is easy and can leverage the application’s performance.

When we say real-time application, we can think of many different applications that can benefit from the use of WebSockets. Chat applications make use of WebSockets because real-time communication between users is the core essential feature of such an app.

Another application type that can benefit a lot from WebSockets is gaming applications. Imagine something like a streaming platform or a game itself. The server should be able to send and receive data uninterrupted in this kind of application.

Conclusion

WebSocket is an amazing protocol for creating two-way communication between a client (e.g., a browser) and a server. It eases the process of sending and receiving data from one party to another.

For developers, it’s a blessing to be able to create real-time applications with such wonderful technologies. It opens a new world of possibilities. There are various use cases that we can think that we can benefit from the usage of WebSockets.

We can create powerful applications nowadays by simply using WebSocket and React. The possibilities are huge. Any kind of real-time application that we want can be created and developed using both technologies. I’d encourage you to give it a try and use WebSockets and React together. They make a great fit and the results will amaze you.


Leonardo Maldonado
About the Author

Leonardo Maldonado

Leonardo is a full-stack developer, working with everything React-related, and loves to write about React and GraphQL to help developers. He also created the 33 JavaScript Concepts.

Related Posts

Comments

Comments are disabled in preview mode.