Blog>
Snippets

Implementing Lazy Loading in React TanStack Table

Illustrate how to implement lazy loading of data in React TanStack Table, fetching more data as the user scrolls, to improve the performance with large datasets.
import { useState, useEffect } from 'react';
import { useTable } from 'tanstack-table';
Import necessary hooks from React and useTable from TanStack Table.
const fetchData = async (page) => {
  // Replace this URL with the actual URL to fetch data
  const response = await fetch(`https://example.com/data?page=${page}`);
  const data = await response.json();
  return data;
};
Define a function to fetch data. This function takes a page number as an argument and fetches data for that page.
const MyTable = () => {
  const [data, setData] = useState([]);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const loadMoreData = async () => {
      setLoading(true);
      const newData = await fetchData(page);
      setData((prevData) => [...prevData, ...newData]);
      setLoading(false);
    };
    loadMoreData();
  }, [page]);
Create a component that uses the fetchData function. It keeps track of the loaded data, the current page, and a loading state. When the component mounts or the page state changes, it fetches new data and appends it to the existing data.
const handleScroll = (e) => {
  const { scrollTop, clientHeight, scrollHeight } = e.currentTarget;
  if (scrollHeight - scrollTop === clientHeight) {
    setPage((prevPage) => prevPage + 1);
  }
};
Define an event handler that triggers loading more data when the user scrolls to the bottom of the table.
return (
  <div onScroll={handleScroll} style={{ overflow: 'auto', height: '400px' }}>
    {/* Render table rows here using data state */}
    {loading && <div>Loading more data...</div>}
  </div>
);
Render the table inside a scrollable div. Attach the handleScroll function to the onScroll event of the div. Display a loading message when more data is being loaded.
};

export default MyTable;
Export the MyTable component.