DEV Community

Cover image for Real-Time Data Visualization in React using WebSockets and Charts
Phinter Atieno for Syncfusion, Inc.

Posted on • Originally published at syncfusion.com on

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 and the Sycfusion React 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

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:

mkdir realtime-websocket-app
cd realtime-websocket-app

Enter fullscreen mode Exit fullscreen mode

Step 2: Initialize a new Node.js project

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

npm init -y

Enter fullscreen mode Exit fullscreen mode

Step 3: Install the WebSocket Library

Next, install the WebSocket library by running the command:

npm install ws

Enter fullscreen mode Exit fullscreen mode

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.

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

Enter fullscreen mode Exit fullscreen mode

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.

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 }));

Enter fullscreen mode Exit fullscreen mode

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.

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

Enter fullscreen mode Exit fullscreen mode

Step 5: Run your WebSocket server

Start your WebSocket server by executing the following command:

node server.js

Enter fullscreen mode Exit fullscreen mode

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, 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 for comprehensive setup instructions and dependencies.

Building the React Charts component

In our app, we’re implementing a spline series chart 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 Splie Chart:

Step 1: Install dependencies

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

npm install @syncfusion/ej2-react-charts

Enter fullscreen mode Exit fullscreen mode

Step 2: Importing required modules

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

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

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

Enter fullscreen mode Exit fullscreen mode

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.

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

Enter fullscreen mode Exit fullscreen mode

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.

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

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

Enter fullscreen mode Exit fullscreen mode

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.

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);
      }
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

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.

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

Enter fullscreen mode Exit fullscreen mode

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 documentation. This setup ensures a responsive, clean real-time updating chart with improved data visualization.

<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>

Enter fullscreen mode Exit fullscreen mode

Step 5: Run the app

Finally, run the react app using the following command:

npm start
Enter fullscreen mode Exit fullscreen mode

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

Visualizing real-time data using WebSocket and React Spline Chart


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.

Conclusion

Thanks for reading! In this blog, we built a real-time data visualization app using WebSockets and Syncfusion React 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® from the License and Downloads page. If you are not a customer, try our 30-day free trial to check out these features.

If you have questions, contact us through our support forum, feedback portal, or support portal. We are always happy to assist you!

Related Blogs

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay