Blog>
Snippets

Implementing Lazy Loading for Large Datasets in Charts

Illustrate how to implement lazy loading for charts that need to render large datasets, loading data in chunks as the user scrolls or interacts with the chart to improve performance.
const [chartData, setChartData] = useState([]);
Initialize state for chart data.
const [isLoading, setIsLoading] = useState(false);
State to track loading status.
const fetchChartData = async (start, end) => {
  setIsLoading(true);
  // Fetch data chunk based on start & end
  const dataChunk = await fetchData(start, end);
  setChartData((prevData) => [...prevData, ...dataChunk]);
  setIsLoading(false);
};
Function to fetch chart data in chunks based on provided start and end indices.
useEffect(() => {
  const handleScroll = () => {
    // Implement logic to detect when user is close to the bottom
    // of the chart or a designated trigger point to load more data
    if (window.innerHeight + document.documentElement.scrollTop === document.documentElement.offsetHeight) {
      const nextStart = chartData.length;
      // Load the next chunk of data
      fetchChartData(nextStart, nextStart + 100); // Example: load next 100 records
    }
  };

  window.addEventListener('scroll', handleScroll);
  return () => window.removeEventListener('scroll', handleScroll);
}, [chartData]);
Effect hook to add scroll event listener. Detaches listener on cleanup to avoid memory leaks.
if (isLoading) return <div>Loading...</div>;
return (
  <div>
    {/* Render chart here with chartData */}
  </div>
);
Render method to display loading indicator or the chart with the data loaded so far.