# Real-Time Data Visualization in React using WebSockets and Charts

**TL;DR:** Let’s see how to build a real-time data visualization app using WebSockets and the Syncfusion React Spline Chart. We’ll set up a WebSocket server in Node.js to stream live data updates. Then, we’ll integrate WebSockets into a React app and dynamically update the Spline Chart with real-time data. This approach ensures smooth and efficient visualization for financial dashboards, live analytics, and more.

Welcome to our latest post in the **Weekly Data Visualization** blog series!

Real-time data updates are crucial in various apps, such as financial dashboards, live analytics, and collaborative tools. In this blog, we’ll delve into creating a real-time data visualization app using [WebSockets](https://en.wikipedia.org/wiki/WebSocket#:~:text=WebSocket%20is%20a%20computer%20communications,as%20RFC%206455%20in%202011.) and the Sycfusion [React Spline Chart](https://www.syncfusion.com/react-components/react-charts/chart-types/spline-chart).

## Understanding WebSocket

WebSockets provides a two-way communication channel over a single TCP connection, allowing real-time data exchange between the server and client. Unlike traditional HTTP requests, which require continuous checking to fetch new data, WebSockets establish a persistent connection, enabling instant data updates with minimal overhead. This makes them an excellent choice for real-time apps like financial dashboards, live analytics, and collaborative tools.

## Prerequisites

* [Node.js](https://nodejs.org/en) and [npm](https://www.npmjs.com/)
    
* [Visual Studio Code](https://code.visualstudio.com/)
    

## Setting up the WebSocket server

We’ll use Node.js to create a WebSocket server that manages real-time data transmission by sending continuous data updates to clients.

### Step 1: Create a new directory for your project

Open Visual Studio Code on your machine, which will serve as your development environment. Create a new directory for the project using the following terminal:

```bash
mkdir realtime-websocket-app
cd realtime-websocket-app
```

### Step 2: Initialize a new Node.js project

Inside your project directory, run the following command to create a new **package.json** file.

```bash
npm init -y
```

### Step 3: Install the WebSocket Library

Next, install the WebSocket library by running the command:

```bash
npm install ws
```

### Step 4: Create the server script

In Visual Studio Code, we need to create a new file named **server.js**. Then, follow these steps to set up the WebSocket server:

**1\. Create a WebSocket server on Port 8080:** Begin by importing the WebSocket module and setting up the server to listen on Port 8080. Here, the WebSocket server gets initialized and listens for client connections. When a client connects, the server executes the callback function inside the **on(‘connection’)** event.

Refer to the following code.

```javascript
const WebSocket = require('ws');
const wss = new WebSocket.Server({port: 8080});
wss.on('connection', (ws) => {
});
```

**2\. Set initial data:** The **initialData** array is populated with 10 objects, each containing the values:

* **x**: A timestamp representing the last 10 seconds.
    
* **y**: A randomly generated value.
    

Once the data is generated, it is sent to the client in JSON format using the **ws.send()** method.

```javascript
const initialData = [];
for (let i = 0; i < 10; i++) {
  initialData.push({
    x: new Date().getTime() - (10 - i) * 1000,
    y: getRandomYValue()
  });
}
ws.send(JSON.stringify({ initialData }));
```

**3\. Send updates every second:** After sending the initial dataset, the server sends a new data point every second using the **setInterval** method. The **x** value represents the current timestamp, while the **y** value is a new random number. The updated data is then sent to the client using WebSocket communication, ensuring real-time updates.

```javascript
setInterval(() => {
  const updateData = {x: new Date().getTime(), y: getRandomYValue()};
  ws.send(JSON.stringify({ updateData }));
}, 1000);
```

### Step 5: Run your WebSocket server

Start your WebSocket server by executing the following command:

```bash
node server.js
```

This command will start the server and listen for incoming WebSocket connections on port 8080.

## Create the React app

To visualize real-time data, we’ll use our [React Charts library](https://www.syncfusion.com/react-components/react-charts), which offers various chart types, including the Spline Chart. Here, we’ll use WebSockets for live data feeds displayed in the chart.

### Getting started

First, refer to the [getting started with React Charts documentation](https://ej2.syncfusion.com/react/documentation/chart/getting-started) for comprehensive setup instructions and dependencies.

### Building the React Charts component

In our app, we’re implementing a [spline series chart](https://ej2.syncfusion.com/react/documentation/chart/chart-types/spline) to dynamically update data from a WebSocket server. This approach is particularly helpful for situations demanding smooth curve visualizations of incoming real-time data.

Let’s follow these steps to configure the React Spline Chart:

#### Step 1: Install dependencies

First, we need to install the required dependencies using **npm**.

```bash
npm install @syncfusion/ej2-react-charts
```

#### Step 2: Importing required modules

Once the dependencies are installed, import the required Syncfusion components in the React project.

```javascript
import React, { useEffect, useRef } from 'react';

import { 
  ChartComponent, 
  SeriesCollectionDirective, 
  SeriesDirective, 
  Inject, 
  SplineSeries, 
  DataLabel, 
  DateTime 
} from '@syncfusion/ej2-react-charts';
```

#### Step 3: Setting up WebSocket for real-time data

**1\. Initialize WebSocket connection:** Create an instance of WebSocket to establish a connection with the WebSocket server. The **onopen** event is triggered when the WebSocket connection is successfully established. This event confirms that the client can now send and receive data.

```javascript
const socket = new WebSocket('ws://localhost:8080');
socket.onopen = () => { 
  console.log('WebSocket connection opened'); 
};
```

**2\. Handle incoming data (onmessage):** When the server sends data, the **onmessage** event is triggered. We parse the received JSON data and update the initial data to the chart’s **datasource** from the WebSocket.

```javascript
socket.onmessage = (event) => {
  const data = JSON.parse(event.data);

  if (data.initialData && chartRef.current) {
    chartRef.current.series[0].dataSource = data.initialData;
  }
};
```

**3\. Add and remove data points dynamically:** Once the initial data is loaded into the chart, periodically update it by adding new data points and removing old ones using **addPoint** and **removePoint** methods. This ensures that the chart remains visually manageable and does not overflow with excessive data.

```javascript
if (data.updateData) {
  if (chartRef.current) {
    const seriesCollection = chartRef.current.series[0] as CustomSeriesModel;
    if (seriesCollection) {
      seriesCollection.addPoint({x: data.updateData.x, y: data.updateData.y }, 860);
      if (seriesCollection.points.length > maxPoints) {
        seriesCollection.removePoint(0, 860);
      }
    }
  }
}
```

**4\. Handle WebSocket closure:** If the WebSocket connection is closed (whether by the server or client), the **onclose** event ensures that resources are properly freed.

```javascript
socket.onclose = () => { 
  console.log('WebSocket connection closed'); 
};
```

### Step 4: Configuring the React Spline Chart

The Chart component is configured with a **DateTime X-axis** and a **Numeric Y-axis** for real-time data visualization. The primary XAxis uses valueType: DateTime to display time-based data dynamically. The SeriesDirective binds **xName** to **x** and **yName** to **y** values and uses the Spline type for smooth curves.

Injected services include **SplineSeries, DateTime,** and **DataLabel** for enhanced chart functionality. For more details on injectable modules, refer to our [Feature Modules](https://ej2.syncfusion.com/react/documentation/chart/feature-modules) documentation. This setup ensures a responsive, clean real-time updating chart with improved data visualization.

```javascript
<ChartComponent
  id="charts"
  ref={chartRef}
  primaryXAxis={{
    valueType: 'DateTime',F
    labelFormat: 'hh:mm:ss',
    intervalType: 'Seconds',
    edgeLabelPlacement: 'Shift',
    majorGridLines: {width: 0},
    lineStyle: {width: 0}
  }}
  primaryYAxis={{
    labelFormat: '{value}', title: 'Value',
    lineStyle: {width: 0}
  }}
>
  <Inject services={[LineSeries, SplineSeries, DataLabel, DateTime]} />
  <SeriesCollectionDirective>
    <SeriesDirective
      dataSource={[data]}
      xName="x"
      yName="y"
      type="Spline"
    />
  </SeriesCollectionDirective>
</ChartComponent>
```

### Step 5: Run the app

Finally, run the react app using the following command:

```bash
npm start
```

Now, our chart will display real-time data with smooth spline curves!

![Visualizing real-time data using WebSocket and React Spline Chart](https://www.syncfusion.com/blogs/wp-content/uploads/2025/03/Real-time-data-display-with-smooth-spline-curves-2.gif align="center")

Visualizing real-time data using WebSocket and React Spline Chart

## GitHub reference

For more details, refer to the [real-time data visualization in a React app using WebSockets and Spline Chart GitHub demo](https://github.com/SyncfusionExamples/Building-a-Real-Time-Data-Visualization-Web-App-with-WebSocket-and-Syncfusion-React-Chart).

## Conclusion

Thanks for reading! In this blog, we built a real-time data visualization app using WebSockets and Syncfusion [React Spline Chart](https://www.syncfusion.com/react-components/react-charts/chart-types/spline-chart). The WebSocket server continuously sends data updates, and the React app dynamically updates the chart. This setup can be extended to monitor live data such as stock prices, IoT sensors, or real-time analytics.

Stay tuned for more updates on real-time web apps!

Existing customers can download the latest version of Essential Studio<sup>®</sup> from the [License and Downloads](https://www.syncfusion.com/account) page. If you are not a customer, try our 30-day [free trial](https://www.syncfusion.com/downloads) to check out these features.

If you have questions, contact us through our [support forum](https://www.syncfusion.com/forums), [feedback portal](https://www.syncfusion.com/feedback), or [support portal](https://support.syncfusion.com/). We are always happy to assist you!

## Related Blogs

* [Analyze Stock Market Trends with React DataGrid for Smart Trading](https://www.syncfusion.com/blogs/post/analyze-stocks-trends-with-react-grid)
    
* [How to Use Dual-Axis Charts for Effective Data Visualization?](https://www.syncfusion.com/blogs/post/view-data-in-react-dual-axis-chart)
    
* [Easily Create UML Activity Diagrams with React Diagram Library](https://www.syncfusion.com/blogs/post/uml-activity-diagram-in-react-diagram)
    
* [Create AI-Assisted Mind Maps Using OpenAI and React Diagram Library](https://www.syncfusion.com/blogs/post/ai-assisted-mind-map-in-react-diagram)
