Web Development 1 min read 945 views

Building Real-time Dashboards with React and WebSockets

Create interactive real-time dashboards using React, WebSockets, and Chart.js. Perfect for monitoring and analytics applications.

E
Dashboard analytics

Building Real-time Dashboards

Create live updating dashboards with React and WebSockets.

WebSocket Server (Node.js)

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

wss.on('connection', (ws) => {
    // Send data every second
    const interval = setInterval(() => {
        ws.send(JSON.stringify({
            cpu: Math.random() * 100,
            memory: Math.random() * 100,
            requests: Math.floor(Math.random() * 1000),
            timestamp: new Date().toISOString(),
        }));
    }, 1000);

    ws.on('close', () => clearInterval(interval));
});

React Dashboard Component

import { useState, useEffect } from 'react';
import { Line } from 'react-chartjs-2';

function Dashboard() {
    const [metrics, setMetrics] = useState([]);

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

        ws.onmessage = (event) => {
            const data = JSON.parse(event.data);
            setMetrics(prev => [...prev.slice(-59), data]);
        };

        return () => ws.close();
    }, []);

    return (
        <div className="grid grid-cols-2 gap-4">
            <MetricCard title="CPU" value={metrics[metrics.length - 1]?.cpu} />
            <MetricCard title="Memory" value={metrics[metrics.length - 1]?.memory} />
            <Line data={chartData} options={chartOptions} />
        </div>
    );
}

Metric Card Component

function MetricCard({ title, value }) {
    return (
        <div className="bg-white rounded-lg shadow p-4">
            <h3 className="text-gray-500 text-sm">{title}</h3>
            <p className="text-3xl font-bold">{value?.toFixed(1)}%</p>
        </div>
    );
}

Combine WebSockets with charting libraries for powerful real-time visualizations.

Share this article:
ES

Written by Edrees Salih

Full-stack software engineer with 9 years of experience. Passionate about building scalable solutions and sharing knowledge with the developer community.

View Profile

Comments (0)

Leave a Comment

Your email will not be published.

No comments yet. Be the first to share your thoughts!