Getting Real-Time Updates in React JS: Polling vs WebSocket
Tags: react, websockets, polling, realtimeupdates
Published: 2023-07-18 04:41:49

![hello](https://i.pinimg.com/originals/57/5a/20/575a20918d349a354cc636a0d49b35a0.gif)

Usually, when a client gets the data from a server, it sends a request to the server, and the server then sends the response (or requested data) back. The issue with this process is we don't get the new data on the client side as soon as the new data is available to the server. 

Now let's say we want real-time updates on our web application. How do we do that!?

First, let us understand what polling is. 

### Polling

Well, polling is a technique in which the client sends the request repeatedly to the server after a fixed interval. This way, the client can check if the server has new information and update the client side accordingly.

This can be implemented in React JS with the help `useEffect` and `setInterval`. Let's see how: -

```
useEffect(() => {
    const interval = setInterval(() => {
        // API call to get data from the server
    }, 5000)

    return () => {
        clearInterval(interval);
    }
}, []);
```

In the example above, a callback function inside `useEffect` runs when the interface loads. The callback function uses `setInterval` to make an API call to the server and gets the data. The API call happens after every 5 seconds.

#### Disadvantages of polling

Even though polling can get us the updates from the server every few intervals, it has disadvantages. Issues with polling are: -

1. It increases the network load because the client has to keep making the API calls after fixed intervals.
2. Low latency because the server processes the API request every time the request is sent.
3. Delayed update since a new connection establishes after a fixed interval which can potentially delay an update.


To overcome these issues, we can use something like WebSocket API and get the updates on the client side as soon as the new data is available on the server (real-time).


### WebSocket API

The WebSocket API uses something known as WebSocket communication. The WebSocket communication allows the client to have a real-time two-way connection and provides events and javascript methods that interact with the server. 

Implementation in React JS: -

```
useEffect(() => {
    // Establish the connection
    const socket = new WebSocket(api_url);

    // To receive messages from the server
    socket.onmessage = (event) => {
        const msg = event.data;
        // Do something with msg
    }

    return () => {
        // Close the connection
        socket.close();
    }

}, []);
```

The above example is a basic implementation of WebSocket API. Step 1 is to establish the connection. When `new WebSocket` is invoked, it initiates a connection between the client and the specified URL.

After the connection is established, the client can get the messages via an onmessage event. The client can utilize other events and methods such as onerror, onopen, onclose, send(), close(), etc.

Follow the [link](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications) for more details.

In the case of WebSocket API, the connection remains open, unlike polling, where the connection terminates after the client receives the data from the server. 

Since the WebSocket connection remains open, the client receives real-time data updates from the server without delay. Additionally, the client does not have to make multiple API calls to fetch the updates reducing the load on the network.

These factors make WebSocket connections favorable for apps requiring real-time updates like chat applications, collaborative editing tools, and many more.


>Note: The server sent events by Chat GPT API can be handled via WebSocket too.