Lazy Loading Data with Row Models
Illustrate how to utilize row models to lazily load data as the user scrolls, enhancing performance for large datasets.
import { useState, useEffect } from 'react';
Importing necessary hooks from React for state management and side effects.
import InfiniteScroll from 'react-infinite-scroll-component';
Importing the InfiniteScroll component to handle lazy loading.
// Simulate fetching data from an API
const fetchData = async (page) => {
const response = await fetch(`https://myapi.com/data?page=${page}`);
const data = await response.json();
return data;
};
Defining a function to simulate fetching data lazily from an API by page.
const LazyLoadedTable = () => {
const [data, setData] = useState([]);
const [page, setPage] = useState(1);
const [hasMore, setHasMore] = useState(true);
useEffect(() => {
const loadInitialData = async () => {
const initialData = await fetchData(page);
setData(initialData);
};
loadInitialData();
}, []);
Setting up the LazyLoadedTable component with state for data, pagination, and control to determine if there's more data to load. Initial data is loaded once on component mount.
const fetchMoreData = async () => {
const newPage = page + 1;
const newData = await fetchData(newPage);
if(newData.length === 0) setHasMore(false);
setData([...data, ...newData]);
setPage(newPage);
};
Defining a function within the component to fetch more data as the user scrolls. It increments the page, fetches data for that new page, and updates the state accordingly.
return (
<InfiniteScroll
dataLength={data.length}
next={fetchMoreData}
hasMore={hasMore}
loader={<h4>Loading...</h4>}
endMessage={<p style={{ textAlign: 'center' }}>
<b>Yay! You have seen it all</b>
</p>}
>
{data.map((item, index) => (
<div key={index}>
{item.title}
</div>
))}
</InfiniteScroll>
);
Rendering the component using InfiniteScroll to lazily load additional rows as the user scrolls. It utilizes the data, fetchMoreData function, and hasMore state to manage the loading process.
};
export default LazyLoadedTable;
Completing the LazyLoadedTable component with export statement for use in other parts of the application.