Blog>
Snippets

Updating Data in Real-time with TanStack React Charts

Shows how to dynamically update the data displayed in a TanStack React Chart without causing unnecessary re-renders, ensuring smooth user experience in real-time applications.
import { useState, useEffect } from 'react';
import { LineChart, Line } from 'recharts';
Import necessary hooks from React and components from Recharts, one of the libraries supported by TanStack for charts.
const DynamicChart = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    const interval = setInterval(() => {
      const newDataSet = data.length > 0 ? [...data, { uv: Math.random() * 4000, pv: 2400, amt: 2400 }] : [{ uv: Math.random() * 4000, pv: 2400, amt: 2400 }];
      if(newDataSet.length > 10) newDataSet.shift();
      setData(newDataSet);
    }, 2000);

    return () => clearInterval(interval);
  }, [data]);

  return (
    <LineChart width={500} height={300} data={data}>
      <Line type="monotone" dataKey="uv" stroke="#8884d8" />
    </LineChart>
  );
};
Defines a DynamicChart component that initially sets data state to an empty array. A useEffect hook updates data every 2 seconds with new random values and keeps the data array to a max of 10 items for demo purposes. This demonstrates how to dynamically update chart data in real-time applications without causing unnecessary re-renders.