Blog>
Snippets

Initializing TanStack React Chart with Dynamic Data

Shows how to set up a basic line chart using TanStack React Charts and dynamically update the data set using React state.
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() {
  // Initialize the chart data state
  const [data, setData] = useState([
    {
      label: 'Series 1',
      data: []
    }
  ]);

  // Dynamically update the data
  useEffect(() => {
    const timer = setInterval(() => {
      setData(currentData => [
        {
          ...currentData[0],
          data: [...currentData[0].data, { x: Date.now(), y: Math.random() * 100 }]
        }
      ]);
    }, 1500);

    return () => clearInterval(timer);
  }, []);
Set up a React component with state for chart data and dynamically update it every 1.5 seconds using useEffect.
const axes = React.useMemo(
    () => [
      { primary: true, type: 'linear', position: 'bottom', show: false },
      { type: 'linear', position: 'left', show: false }
    ],
    []
  );
Define the axes for the chart, marking one as primary and setting their positions.
return (
    <div
      style={{
        width: '400px',
        height: '300px'
      }}
    >
      <Chart data={data} axes={axes} />
    </div>
  );
}
Render the chart in a container div, providing the dynamic data and configured axes as props to the Chart component.
export default MyChart;
Export the MyChart component for use in the application.