Back to Blog
IoT Dashboard

Building Real-Time IoT Dashboards with React and Recharts

Recharts is the most popular React charting library, but making it work with live IoT data requires careful state management, smart data windowing, and preventing re-render storms. Here's the production architecture we use.

September 22, 2024
12 min read
ReactRechartsIoT DashboardWebSocket

Building Real-Time IoT Dashboards with React and Recharts

React dashboards that poll REST APIs every second are the wrong approach for IoT. You get stale data, unnecessary server load, and poor UX. The right stack is WebSocket for real-time push, Recharts for visualization, and careful state management to prevent re-render hell.

This guide builds a production-grade IoT dashboard that handles 50+ devices updating every second without the UI becoming a slideshow.

Architecture

IoT Devices → MQTT Broker → Node.js WebSocket Server
                                      ↓
                              React Dashboard
                              ├── useWebSocket hook
                              ├── useReducer (telemetry store)
                              └── Recharts (charts)

Step 1: WebSocket Hook

// hooks/useWebSocket.ts
import { useEffect, useRef, useCallback } from 'react'

interface WebSocketHookOptions { url: string onMessage: (data: unknown) => void onConnect?: () => void onDisconnect?: () => void }

export function useWebSocket({ url, onMessage, onConnect, onDisconnect }: WebSocketHookOptions) { const ws = useRef(null) const reconnectTimer = useRef>() const attempts = useRef(0)

const connect = useCallback(() => { ws.current = new WebSocket(url)

ws.current.onopen = () => { attempts.current = 0 onConnect?.() }

ws.current.onmessage = (event) => { try { const data = JSON.parse(event.data) onMessage(data) } catch {} }

ws.current.onclose = () => { onDisconnect?.() const delay = Math.min(30000, 1000 * 2 ** attempts.current) attempts.current++ reconnectTimer.current = setTimeout(connect, delay) }

ws.current.onerror = () => ws.current?.close() }, [url, onMessage, onConnect, onDisconnect])

useEffect(() => { connect() return () => { clearTimeout(reconnectTimer.current) ws.current?.close() } }, [connect])

const send = useCallback((data: unknown) => { if (ws.current?.readyState === WebSocket.OPEN) { ws.current.send(JSON.stringify(data)) } }, [])

return { send } }

Step 2: Telemetry State with useReducer

Never use useState for accumulating IoT data — useReducer gives you predictable updates and prevents stale closures:

// store/telemetry.ts
export interface DataPoint {
  ts:          number
  temperature: number
  humidity:    number
  voltage:     number
}

export interface DeviceTelemetry { deviceId: string label: string isOnline: boolean history: DataPoint[] // Rolling 60-point window latest: DataPoint | null }

type Action = | { type: 'UPDATE_DEVICE'; deviceId: string; point: DataPoint } | { type: 'SET_OFFLINE'; deviceId: string } | { type: 'INIT_DEVICES'; devices: { deviceId: string; label: string }[] }

const HISTORY_WINDOW = 60 // Last 60 data points per device

export function telemetryReducer( state: Record, action: Action, ): Record { switch (action.type) { case 'UPDATE_DEVICE': { const existing = state[action.deviceId] if (!existing) return state

const newHistory = [...existing.history, action.point].slice(-HISTORY_WINDOW) return { ...state, [action.deviceId]: { ...existing, isOnline: true, latest: action.point, history: newHistory, }, } } case 'SET_OFFLINE': return { ...state, [action.deviceId]: { ...state[action.deviceId], isOnline: false }, } case 'INIT_DEVICES': { const init: Record = {} for (const d of action.devices) { init[d.deviceId] = { ...d, isOnline: false, history: [], latest: null } } return init } } }

Step 3: Dashboard Component

// Dashboard.tsx
import { useReducer, useCallback } from 'react'
import { telemetryReducer } from './store/telemetry'
import { useWebSocket } from './hooks/useWebSocket'
import { DevicePanel } from './DevicePanel'

export function Dashboard() { const [devices, dispatch] = useReducer(telemetryReducer, {})

const handleMessage = useCallback((data: unknown) => { const msg = data as { type: string; deviceId: string; payload: any }

if (msg.type === 'telemetry') { dispatch({ type: 'UPDATE_DEVICE', deviceId: msg.deviceId, point: { ts: Date.now(), temperature: msg.payload.temperature, humidity: msg.payload.humidity, voltage: msg.payload.voltage, }, }) }

if (msg.type === 'device_offline') { dispatch({ type: 'SET_OFFLINE', deviceId: msg.deviceId }) } }, [])

useWebSocket({ url: ${process.env.REACT_APP_WS_URL}/dashboard, onMessage: handleMessage, })

return (

{Object.values(devices).map(device => ( ))}
) }

Step 4: Recharts Live Chart

// DevicePanel.tsx
import { memo } from 'react'
import {
  LineChart, Line, XAxis, YAxis, CartesianGrid,
  Tooltip, ResponsiveContainer
} from 'recharts'
import type { DeviceTelemetry } from './store/telemetry'

interface Props { device: DeviceTelemetry }

// memo() prevents re-render when OTHER devices update export const DevicePanel = memo(function DevicePanel({ device }: Props) { const chartData = device.history.map((pt, i) => ({ index: i, temperature: pt.temperature, humidity: pt.humidity, ts: new Date(pt.ts).toLocaleTimeString(), }))

return (

{device.label}

{device.isOnline ? '● Online' : '○ Offline'}

{device.latest && (

${device.latest.temperature.toFixed(1)}°C} color="text-orange-400" /> ${device.latest.humidity.toFixed(0)}%} color="text-blue-400" /> ${device.latest.voltage.toFixed(2)}V} color="text-green-400" />
)}

) })

const Stat = ({ label, value, color }: { label: string; value: string; color: string }) => (

text-lg font-mono font-bold ${color}}>{value}
{label}
)

Critical performance notes:

  • 1. isAnimationActive={false} — Recharts animations on real-time data cause jank
  • 2. memo() — each DevicePanel only re-renders when its own device data changes
  • 3. useCallback on handleMessage — prevents WebSocket hook from reconnecting on every render
  • Step 5: Performance Optimizations

    For 50+ devices updating every second:

    // Throttle UI updates — don't re-render more than 2×/second per device
    import { throttle } from 'lodash'

    const handleMessage = useCallback( throttle((data: unknown) => { // dispatch updates }, 500), // 500ms = max 2 renders/sec [], )

    // Virtualize the device grid for large fleets import { FixedSizeGrid } from 'react-window'

    // For 100+ devices, use react-window instead of a flat grid

    Need a production IoT dashboard built for your fleet? [Contact Code Caracal](/contact) — we've built dashboards monitoring thousands of real-time devices.

    Written by CodeCaracal Engineering

    We write from production experience — every technique in our articles has been deployed to real clients. No academic theory.

    More Articles

    Business · 12 min read

    IoT Device Compliance: FCC, CE, and Product Certification Guide for Hardware Startups

    Business · 11 min read

    What to Look for When Hiring an IoT Development Partner: 8 Critical Criteria

    Business · 11 min read

    IoT MVP to Production: Realistic Timeline and Budget for Hardware Startups

    Business · 11 min read

    IoT Development Agency vs Building In-House: A Decision Framework for Founders

    IoT Dashboard · 13 min read

    Next.js IoT Analytics Dashboard: From Sensor Data to Production App

    Business · 11 min read

    How Much Does It Cost to Build an IoT Product in 2024? A Realistic Breakdown

    IoT Dashboard · 11 min read

    IoT Dashboard UX: Design Principles for Industrial Monitoring Interfaces

    IoT Dashboard · 12 min read

    Node.js WebSocket Server: The Real-Time Backend for IoT Dashboards

    Cloud & DevOps · 12 min read

    Containerizing IoT Backend Services with Docker: From Dev to Production

    IoT Dashboard · 14 min read

    Grafana + InfluxDB IoT Monitoring: Complete Production Setup Guide

    Cloud & DevOps · 13 min read

    CI/CD for Embedded Firmware: Automated Build, Test, and OTA Release Pipeline

    Mobile Development · 12 min read

    Flutter Offline-First IoT Apps: Hive + Sync Architecture That Works in the Field

    Cloud & DevOps · 14 min read

    Terraform for IoT Infrastructure: Provisioning AWS IoT Core, Lambda, and InfluxDB as Code

    Mobile Development · 10 min read

    Flutter IoT Alerts: Firebase Push Notifications for Device Events

    Cloud & DevOps · 12 min read

    Deploying IoT Backends on AWS: ECS Fargate vs Lambda vs EC2 Decision Guide

    Mobile Development · 11 min read

    Flutter + MQTT: Building Production IoT Mobile Apps That Scale

    Mobile Development · 13 min read

    Flutter BLE: Building a Bluetooth IoT Controller App from Scratch

    Cloud & DevOps · 13 min read

    AWS IoT Core vs Azure IoT Hub vs Google Cloud IoT: 2024 Honest Comparison

    IoT Engineering · 13 min read

    Kafka vs RabbitMQ for IoT: Choosing the Right Message Queue for High-Volume Telemetry

    IoT Engineering · 14 min read

    IoT System Testing: Unit, Integration, Hardware-in-the-Loop, and End-to-End

    IoT Engineering · 14 min read

    Predictive Maintenance with IoT Sensor Data: From Threshold to Machine Learning

    Embedded Systems · 14 min read

    IoT Bootloader Design: Secure Boot, A/B Partitions, and Reliable OTA Recovery

    IoT Engineering · 14 min read

    Multi-Tenant IoT Platform Architecture: Isolation, Scaling, and Data Partitioning

    Embedded Systems · 14 min read

    Memory Management in Embedded Firmware: Avoiding Heap Fragmentation and Stack Overflows

    IoT Engineering · 13 min read

    IoT Cost Optimization: How We Cut AWS IoT Bills by 60% Without Sacrificing Reliability

    IoT Engineering · 12 min read

    Edge Computing in IoT: When to Process On-Device vs In the Cloud

    IoT Engineering · 13 min read

    Digital Twins for IoT: Building a Virtual Mirror of Your Physical Devices

    Embedded Systems · 14 min read

    ESP32 Deep Sleep Mastery: Cutting Power Consumption from 240mA to 10µA

    IoT Engineering · 10 min read

    MQTT QoS 0, 1, and 2 Explained: Choosing the Right Level for IoT

    IoT Engineering · 14 min read

    IoT Monitoring and Observability: Metrics, Logs, and Distributed Tracing

    Embedded Systems · 14 min read

    Debugging Embedded Firmware: JTAG, GDB, Logic Analyzers, and Serial Tracing

    IoT Engineering · 12 min read

    WebSocket vs MQTT vs Server-Sent Events: Real-Time IoT Protocol Deep Dive

    Embedded Systems · 13 min read

    STM32 HAL vs Low-Level Drivers: When the Abstraction Costs You Too Much

    IoT Engineering · 13 min read

    IoT Data Pipeline: From Raw Sensor Reading to Live Dashboard in Under 100ms

    IoT Engineering · 13 min read

    Zero-Touch IoT Device Provisioning: Scaling from 10 to 100,000 Devices

    Embedded Systems · 13 min read

    UART vs SPI vs I2C: Choosing the Right Protocol for Sensor Integration

    IoT Engineering · 12 min read

    Real-Time IoT Alerting: From Simple Thresholds to ML Anomaly Detection

    Embedded Systems · 12 min read

    ESP32 Partition Table: Designing Flash Layout for Production Firmware

    IoT Engineering · 12 min read

    IoT Architecture Patterns: Hub-and-Spoke, Mesh, and Edge-Cloud Hybrid

    Embedded Systems · 13 min read

    IoT Battery Life Optimization: Engineering Devices That Last Years on a Single Charge

    IoT Engineering · 13 min read

    Time-Series Databases for IoT: InfluxDB vs TimescaleDB vs AWS Timestream

    Security · 14 min read

    Zero-Trust Security for Embedded IoT: Why Your Devices Are Probably Vulnerable

    Embedded Systems · 14 min read

    FreeRTOS on ESP32: Task Scheduling, Queues, and Resource Management for IoT

    IoT Engineering · 12 min read

    Building a Production IoT Gateway with Raspberry Pi and Node.js

    Embedded Systems · 13 min read

    ESP32 vs STM32: Choosing the Right Microcontroller for Your IoT Project

    Mobile Development · 10 min read

    Flutter + WebSocket: Building Real-Time IoT Dashboards That Don't Stutter

    IoT Engineering · 13 min read

    IoT Fleet Management at Scale: AWS IoT Core Device Registry and Provisioning

    IoT Engineering · 11 min read

    MQTT vs HTTP for IoT: Which Protocol Wins in Production?

    IoT Engineering · 12 min read

    ESP32 → MQTT → AWS IoT Core: The Production-Grade Architecture Guide

    Let's Build Together

    Got an IoT challenge?
    We've shipped it.

    Whether you need a fleet to track, a factory to monitor, or a farm to automate — our team has done it before and we'd love to build it with you. Typical response time: under 24 hours.

    No upfront commitment99.9% uptime SLANDA on requestFixed-price options