Clean β’ Professional
When building modern web apps, displaying large datasets efficiently is a common challenge. Loading hundreds or thousands of items at once can slow down your app and harm user experience. React provides strategies like pagination and infinite scroll to handle large data gracefully, keeping your UI fast and responsive.
Pagination divides data into pages, allowing users to navigate between them.
Example β Simple Pagination:
import React, { useState, useEffect } from "react";
function PaginatedList() {
const [users, setUsers] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 5;
useEffect(() => {
fetch("<https://jsonplaceholder.typicode.com/users>")
.then((res) => res.json())
.then((data) => setUsers(data));
}, []);
const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = users.slice(indexOfFirstItem, indexOfLastItem);
const totalPages = Math.ceil(users.length / itemsPerPage);
return (
<div>
<ul>
{currentItems.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
<div>
{Array.from({ length: totalPages }, (_, i) => (
<button key={i} onClick={() => setCurrentPage(i + 1)}>
{i + 1}
</button>
))}
</div>
</div>
);
}
export default PaginatedList;
users is rendered per page.slice() ensures only the current pageβs data is displayed.Infinite scroll loads more data automatically as the user scrolls, giving a seamless browsing experience.
Example β Infinite Scroll:
import React, { useState, useEffect } from "react";
function InfiniteScrollList() {
const [users, setUsers] = useState([]);
const [visibleCount, setVisibleCount] = useState(5);
useEffect(() => {
fetch("<https://jsonplaceholder.typicode.com/users>")
.then((res) => res.json())
.then((data) => setUsers(data));
}, []);
const loadMore = () => {
setVisibleCount((prev) => prev + 5);
};
return (
<div>
<ul>
{users.slice(0, visibleCount).map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
{visibleCount < users.length && (
<button onClick={loadMore}>Load More</button>
)}
</div>
);
}
export default InfiniteScrollList;