Building Engaging Real-Time Data Visualizations In React With Highcharts

Written by maksymmostovyi | Published 2024/02/12
Tech Story Tags: data-visualization | data-analytics | javascript | reactjs | highcharts | charts | front-end-development | frontend

TLDRTL;DR: This article guides you through building real-time data visualizations in React using Highcharts and WebSocket, complete with step-by-step instructions, practical examples, and a GitHub repository for hands-on learning. Perfect for developers aiming to integrate dynamic charts and graphs into their applications.via the TL;DR App

In the rapidly evolving digital landscape, data visualization plays a crucial role in understanding complex data sets and making informed decisions. Real-time data visualization, which updates dynamically to reflect live data feeds, is particularly powerful for monitoring systems, financial markets, social media trends, and more. This comprehensive guide explores how to leverage React, alongside Highcharts, a versatile charting library, to create real-time charts and graphs that are both engaging and informative.

Understanding the Importance of Real-Time Data Visualization

Real-time data visualization transforms static data presentations into vibrant, continuously updating streams of information. This dynamic approach to data visualization is critical in scenarios where the timely interpretation of data can lead to actionable insights, improved user engagement, or even competitive advantages. Examples include:

  • Financial Dashboards: Stock market traders rely on real-time charts to make quick buy or sell decisions based on the latest market movements.
  • IoT Device Monitoring: Industries use real-time graphs to monitor the performance and health of Internet of Things (IoT) devices, ensuring timely maintenance and operations.
  • Social Media Analytics: Brands track social media sentiment and engagement in real-time to respond to trends, manage crises, or capitalize on viral moments.
  • Sports Analytics: Fans and coaches use real-time data to analyze game performance, make strategic decisions, and enhance viewer engagement.

Step-by-Step Guide to Implementing Real-Time Charts in React with Highcharts

Creating a real-time chart involves setting up a WebSocket server for live data feeds and integrating Highcharts in a React application to visualize the data. Let's dive into a detailed implementation.

Step 1: Bootstrap Your React Application

Start by creating a new React application:

npm create vite@latest

Step 2: Install Highcharts and Its React Wrapper

Highcharts is not only powerful but also easy to integrate with React through its official wrapper:

npm install highcharts highcharts-react-official

Step 3: Set Up a WebSocket Server

For this guide, we'll simulate a WebSocket server that emits random data points, mimicking a live data feed. This server is crucial for demonstrating real-time data flow.

Create a Simple WebSocket Server:

In a new directory or within your project, set up a basic WebSocket server using the ws library.

Server Code:

Create a server.js file, inside it lets write script that periodically sends random data to connected clients:

const WebSocket = require('ws');
// Create a WebSocket server that listens on port 8080. This server will accept WebSocket connections on this port.
const wss = new WebSocket.Server({ port: 8080 });

// Listen for 'connection' events on the WebSocket server. These events are emitted whenever a new client connects to the server.
wss.on('connection', ws => {
    console.log('New client connected!');

    // Use setInterval to create a loop that executes the given function every 3000 milliseconds (3 seconds).
    setInterval(() => {
        // Create an object named 'data' with two properties:
        // 'value' - a random number between 0 and 100,
        // 'timestamp' - the current date and time.
        const data = {
            value: Math.random() * 100,
            timestamp: new Date()
        };

        // Convert the 'data' object to a JSON string and send it to the connected client.
        // The 'ws.send' method is used to send data to a client through the WebSocket connection.
        ws.send(JSON.stringify(data));
    }, 3000); // Update every second
});

console.log('WebSocket server running on port 8080');

Start Your Server:

Run your WebSocket server:

node server.js

Step 4: Integrating Highcharts in React

Now, let's use Highcharts in our React application to visualize the real-time data.

  1. Modify App.jsx:

    Import Highcharts and the HighchartsReact component. Establish a WebSocket connection to receive live data and update the chart accordingly:

import { useState, useEffect } from 'react';
import Highcharts from 'highcharts';
import HighchartsReact from 'highcharts-react-official';

const App = () => {
    const [data, setData] = useState([]);

    useEffect(() => {
        const ws = new WebSocket('ws://localhost:8080');

        // Connection opened
        ws.onopen = () => console.log('WebSocket Connected');

        // Listen for messages
        ws.onmessage = (event) => {
            try {
                const receivedData = JSON.parse(event.data);
                // Convert timestamp to milliseconds since the Unix epoch
                const timestamp = new Date(receivedData.timestamp).getTime();
                const value = receivedData.value;
                const newDataPoint = [timestamp, value]; // Create the Highcharts-expected format

                setData((currentData) => {
                    const newData = [...currentData, newDataPoint];
                    // Sort by timestamp, which is the first element of each data point array.
                    // Also we need to keep only last 15 data points. Otherwise chart will get messy.
                    return newData.sort((a, b) => a[0] - b[0]).slice(-15);
                });
            } catch (error) {
                console.error('Error parsing message data:', error);
            }
        };

        // Listen for possible errors
        ws.onerror = (error) => console.error('WebSocket Error:', error);

        // Clean up function
        return () => {
            if (ws.readyState === WebSocket.OPEN) {
                ws.close();
                console.log('WebSocket Disconnected');
            }
        };
    }, []);

    // Chart configuration options
    const chartOptions = {
        chart: {
            type: 'spline', // Defines the chart type as a spline (smoothed line chart)
            animation: Highcharts.svg, // Enable animation for SVG elements
            marginRight: 10, // Margin on the right side of the chart
        },
        time: {
            useUTC: false, // Use local time instead of UTC
        },
        title: {
            text: 'Live Data Stream', // Chart title
        },
        xAxis: {
            type: 'datetime', // Configure x-axis to display dates and times
            tickPixelInterval: 150, // Distance between each tick mark on the x-axis
        },
        yAxis: {
            title: {
                text: 'Value', // y-axis title
            },
        },
        legend: {
            enabled: false, // Disable chart legend
        },
        series: [{
            name: 'Live Data', // Series name
            data: data, // Chart data sourced from the state
        }],
    };

    return (
        <div
            style={{
                width: '700px',
                height: '400px',
                borderRadius: '8px',
                boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
                backgroundColor: 'white',
                padding: '10px'
            }}
        >
            <HighchartsReact highcharts={Highcharts} options={chartOptions} />
        </div>
    );
};

export default App;

That what we get as a result:

Line chart gets update every 3 seconds.

Wrapping up

Diving into real-time data visualization with React and Highcharts opens a world of possibilities for developers and data enthusiasts alike. To bridge the gap between theory and practice, I have made the entire project available on GitHub. This not only allows you to explore the intricacies of the code but also encourages you to experiment, adapt, and possibly enhance it according to your unique needs or curiosity. Cheers !


Written by maksymmostovyi | Software engineer with expertise in JavaScript, Angular, and React. One of my key skills is Data Visualisation.
Published by HackerNoon on 2024/02/12