Blog>
Snippets

Dynamically Updating Charts with Real-time Scientific Data

Show how to update a TanStack React Chart dynamically with real-time data, such as live sensor readings, using WebSocket for data streaming.
import React, { useState, useEffect } from 'react';
import { Chart } from 'react-charts';
Import necessary modules from React and the Chart component from react-charts.
function MyChart() {
  const [data, setData] = useState([{ label: 'Sensor Data', data: [] }]);
Define a functional component 'MyChart' and initialize chart data state with useState.
useEffect(() => {
    const ws = new WebSocket('ws://data-source.example.com');
    ws.onmessage = (event) => {
        const sensorData = JSON.parse(event.data);
        const newData = [{
            label: 'Sensor Data',
            data: [...data[0].data, sensorData]
        }];
        setData(newData);
    };
    return () => ws.close();
}, [data]);
Utilize useEffect to open a WebSocket connection to the data source, listen for messages, parse the incoming data, and update the chart data state.
const axes = React.useMemo(() => [
    { primary: true, type: 'linear', position: 'bottom' },
    { type: 'linear', position: 'left' }
], []);
Define the axes for the chart using React useMemo for performance optimization.
return (
    <div style={{ height: '300px' }}>
        <Chart data={data} axes={axes} />
    </div>
);
Render the Chart component within the functional component, passing in the data and axes.
}
export default MyChart;
Close the functional component and export it for use in other parts of the application.