Blog>
Snippets

Optimizing Chart Performance with Lazy Loading

Showcase a technique for implementing lazy loading of data in a TanStack React Chart to improve initial load times and performance.
import { useChart } from 'tanstack-react-chart';
import React, { useState, useEffect } from 'react';
Import necessary hooks from React and the useChart hook from tanstack-react-chart.
const LazyLoadChart = ({ dataEndpoint }) => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      const response = await fetch(dataEndpoint);
      const result = await response.json();
      setData(result);
      setLoading(false);
    };
    fetchData();
  }, [dataEndpoint]);
Define a LazyLoadChart component that fetches chart data asynchronously from a specified endpoint only once upon component mount. The data is then stored in a state.
if (loading) return <p>Loading chart data...</p>;

  const chart = useChart({
    data,
    // Define other chart options here
  });

  return <div>{/* Render your chart with loaded data here */}</div>;
};

export default LazyLoadChart;
Render a loading indicator while fetching data. Once data is fetched, initialize the chart with the `useChart` hook using the loaded data, and render the chart in the component.