Blog>
Snippets

Custom Hook for Real-Time Data Updating in Charts

Create a custom React hook that fetches real-time data and updates the chart, demonstrating efficient data fetching and state management for dynamic chart updates.
import { useEffect, useState } from 'react';

export const useRealTimeData = (url) => {
  const [data, setData] = useState([]);

  useEffect(() => {
    const ws = new WebSocket(url);
    ws.onmessage = (event) => {
      const newData = JSON.parse(event.data);
      setData((prevData) => [...prevData, ...newData]);
    };
    return () => ws.close();
  }, [url]);

  return data;
};
Defines a custom React hook, useRealTimeData, which takes a WebSocket URL as an argument. It sets up a WebSocket connection to the provided URL and listens for incoming messages. When a new message is received, it parses the JSON data and updates the state by appending the new data to the existing data array. The hook returns the latest data, allowing a React component to consume and display it. The useEffect cleanup function ensures the WebSocket connection is closed when the component unmounts or the URL changes.
import React from 'react';
import { Line } from 'react-chartjs-2';
import { useRealTimeData } from './useRealTimeData';

const RealTimeChart = ({ url }) => {
  const realTimeData = useRealTimeData(url);

  const chartData = {
    labels: realTimeData.map((item) => item.timestamp),
    datasets: [
      {
        label: 'Real-Time Data',
        data: realTimeData.map((item) => item.value),
        fill: false,
        borderColor: 'rgb(75, 192, 192)',
        tension: 0.1
      }
    ]
  };

  return <Line data={chartData} />;
};
Implements a React component, RealTimeChart, which uses the custom useRealTimeData hook to fetch real-time data from a WebSocket server. This component maps the fetched data to the format expected by react-chartjs-2's Line component, generating a chart that updates in real-time as new data arrives. The chartData object's labels and datasets are dynamically populated with timestamps and values from the incoming data.