Pagination and Infinite Scrolling with React Hooks
Last Updated :
09 May, 2024
In the world of web development, making long lists of items like posts, products, or comments easy to navigate is super important. Two common ways to do this are Pagination and Infinite Scrolling. In this guide, we'll walk through how to implement both of these techniques using React Hooks. Don't worry if you're new to React or programming – we'll take it step by step!
Prerequisite:
Approach to Implement Pagination and Infinite Scrolling with React Hooks
Pagination Approach:
- useState: Utilize the useState hook to manage state variables such as
posts
, loading
, and currentPage
. - useEffect: Fetch data from the API when the
currentPage
changes, using the useEffect hook with a dependency on currentPage
. - Fetch Data: Fetch posts from the API based on the current page using
fetchPosts
function, which updates the posts
state and toggles the loading
state. - Handle Page Change: Implement a
handlePageChange
function to update the currentPage
state when the user navigates between pages. - Render: Render the fetched posts and display a loading indicator while data is being fetched.
Infinite Scroll Approach:
- useState: Similar to pagination, use the useState hook to manage state variables such as
posts
, loading
, page
, and hasMore
. - useEffect: Fetch data from the API when the
page
changes, using the useEffect hook with a dependency on page
. - Fetch Data: Fetch posts from the API based on the current page using
fetchPosts
function, which appends new posts to the existing list and updates the hasMore
state. - Handle Scroll: Implement a
handleScroll
function that triggers when the user scrolls to the bottom of the page. If conditions are met (not loading, more posts available, scrolled to the bottom), increment the page
state. - Render: Render the fetched posts and display a loading indicator while data is being fetched. Also, add a scroll event listener in useEffect to detect scrolling.
Steps to Build a Pagination and Infinite Scrolling With React Hooks
Step 1: Setup a new React App.
npx create-react-app project
Step 2: Navigate to the root directory of your project using the below command.
cd project
Step 3: Check `src` folder.
Inside src folder make changes for Pagination and then for Infinite Scroll. Replace the code inside the App.js.
First we will create Pagination then Infinitescroll. You just have to replace the code of App.js for both.
Pagination
Example: Below is an example of Pagination with React Hooks:
CSS
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.pagination {
display: flex;
justify-content: center;
}
h3 {
margin: 10px;
}
h1 {
background-color: green;
color: aliceblue;
padding: 10px 20px;
}
JavaScript
import React, {
useState,
useEffect
} from 'react';
import './App.css';
const Pagination = () => {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
const [currentPage, setCurrentPage] = useState(1);
useEffect(() => {
fetchPosts();
}, [currentPage]);
const fetchPosts = async () => {
setLoading(true);
try {
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts?_page=${currentPage}&_limit=10`);
const data = await response.json();
setPosts(data);
} catch (error) {
console.error('Error fetching posts:', error);
} finally {
setLoading(false);
}
};
const handlePageChange = (newPage) => {
setCurrentPage(newPage);
};
return (
<div>
<h1>Pagination</h1>
<div className="posts">
{posts.map(post => (
<div key={post.id} className="post">
<h2>{post.title}</h2>
<p>{post.body}</p>
</div>
))}
{loading && <div>Loading...</div>}
</div>
<div className="pagination" >
<button onClick={() => handlePageChange(currentPage - 1)}
disabled={currentPage === 1}>
Previous
</button>
<h3>
{currentPage}
</h3>
<button onClick={() => handlePageChange(currentPage + 1)}>
Next
</button>
</div>
</div>
);
};
export default Pagination;
Start your application using the following command.
npm start
Output:
Infinite Scrolling
Example: Below is an example of Infinite Scrolling With React Hooks:
CSS
/* Write CSS Here */
h1 {
text-align: center;
background-color: green;
color: white;
padding: 10px 20px;
}
h2 {
color: red;
}
JavaScript
import React, {
useState,
useEffect
} from 'react';
import './App.css';
const InfiniteScroll = () => {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
const [page, setPage] = useState(1);
const [hasMore, setHasMore] = useState(true);
useEffect(() => {
fetchPosts();
}, [page]);
const fetchPosts = async () => {
setLoading(true);
try {
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts?_page=${page}&_limit=10`);
const data = await response.json();
setPosts(prevPosts => [...prevPosts, ...data]);
setHasMore(data.length > 0);
} catch (error) {
console.error('Error fetching posts:', error);
} finally {
setLoading(false);
}
};
const handleScroll = () => {
if (!loading && hasMore &&
window.innerHeight + document.documentElement.scrollTop >=
document.documentElement.scrollHeight - 20) {
setPage(prevPage => prevPage + 1);
}
};
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, [loading, hasMore]);
return (
<div>
<h1>Infinite Scroll</h1>
<div className="posts">
{posts.map(post => (
<div key={post.id} className="post">
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
))}
<h2>
{loading && <div>Loading...</div>}
</h2>
</div>
</div>
);
};
export default InfiniteScroll;
Output :
Conclusion
And that's it! You've now learned how to implement pagination and infinite scrolling using React Hooks. These techniques are essential for creating user-friendly interfaces for long lists of data. Feel free to experiment with the code and customize it to fit your needs. Happy coding!
Similar Reads
Implementing Pagination and Infinite Scrolling with React Hooks
This article will discuss pagination and infinite scrolling. These concepts are commonly used in web applications to enhance the user experience. Pagination and infinite scrolling both help in the efficient handling of huge data sizes. Approach to Implement Pagination and Infinite Scrolling:Paginati
6 min read
Implementing Infinite Scrolling with React Hooks
Infinite Scroll is a crucial aspect of many web applications, ensuring that users have access to infinite content while keeping the user experience in mind. In this article, weâll explore how to implement infinite scroll flows in a React application using React Hooks. Prerequisites:NPM and NodeReact
6 min read
How to handle internationalization with Hooks in React ?
Handling internationalization (i18n) involves using the state to manage the current language and updating the UI based on the selected language. This typically includes creating language files or dictionaries for each supported language and dynamically rendering the content based on the selected lan
3 min read
Pagination Component using React Hooks
Pagination on websites refers to the way of displaying a large set of data in smaller chunks. In React, it's super easy to create a pagination component with the help of the `useEffect` and `useState` hooks. we will create a pagination component using React hooks. Output Preview: Let us have a look
3 min read
React Suite Pagination Used with Link in next/link
React suite is a library of React components, sensible UI design, and a friendly development experience. It is supported in all major browsers. It provides pre-built components of React which can be used easily in any web application. In this article, we'll learn about React suite Pagination Used wi
2 min read
How to implement pagination in React using Hooks?
Implementing pagination in React using hooks involves managing the state of the current page and the number of items per page, as well as rendering the paginated data accordingly. Implementing pagination in React using Hooks:Setup Initial State: Use the useState hook to manage the state for the curr
3 min read
How to show pagination in ReactJS ?
Pagination shows the page number and allows users to switch between pages easily with the next and previous buttons. Material UI for React has this component available for us and it is very easy to integrate. Prerequisites:NodeJS or NPMReact JSMaterial UISteps for Creating React Application And Inst
2 min read
React Suite Pagination Component
React Suite is a popular front-end library with a set of React components that are designed for the middle platform and back-end products. Pagination component allows the user to select a specific page from a range of pages. We can use the following approach in ReactJS to use the React Suite Paginat
3 min read
Build an Image Search App with Infinite Scroll using React JS
This article delves into building a React-based image search app with infinite scroll. Users can search for images based on a query, and as they scroll down, additional images are fetched and shown. The Unsplash API is employed for searching and retrieving these images, resulting in a fully operatio
3 min read
ReactJS UI Ant Design Pagination Component
Ant Design Library has this component pre-built, and it is very easy to integrate as well. Pagination Component allows the user to show the page number and switch between pages easily with the next and previous button. We can use the following approach in ReactJS to use the Ant Design Pagination Com
3 min read