Pagination in MongoDB + React: Build an Efficient UI

Aamir Khan
0
Pagination in MongoDB + React: Build an Efficient UI

Pagination in MongoDB + React: Build an Efficient UI

As your application grows, so does the data you need to display. Loading thousands of records in one go isn’t just slow—it can wreck your user experience. That’s where pagination comes in. In this guide, we’ll walk through how to implement efficient server-side pagination using MongoDB and display it cleanly with React.

Whether you’re a junior developer or self-taught coder, mastering pagination is a must-have skill for building scalable apps.

What is Pagination?

Pagination is the process of dividing data into smaller, more manageable chunks (pages) instead of showing it all at once. This keeps your app fast and your users happy.

Why Pagination Matters in MongoDB + React

  • Performance: Only loads the data you need.
  • User Experience: Makes it easier to navigate large datasets.
  • Scalability: Handles growing datasets without overloading your UI.

Implementing Pagination in MongoDB (Backend)

We’ll use limit and skip in MongoDB to fetch specific pages.

app.get('/api/posts', async (req, res) => {
  const page = parseInt(req.query.page) || 1;
  const limit = parseInt(req.query.limit) || 10;
  const skip = (page - 1) * limit;

  const posts = await Post.find().skip(skip).limit(limit);
  const total = await Post.countDocuments();

  res.json({
    data: posts,
    totalPages: Math.ceil(total / limit),
    currentPage: page
  });
});

Implementing Pagination in React (Frontend)

We’ll fetch paginated data and render page buttons dynamically.

import React, { useState, useEffect } from 'react';

function PostList() {
  const [posts, setPosts] = useState([]);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);

  useEffect(() => {
    fetch(`/api/posts?page=${page}&limit=5`)
      .then(res => res.json())
      .then(data => {
        setPosts(data.data);
        setTotalPages(data.totalPages);
      });
  }, [page]);

  return (
    <div>
      <ul>
        {posts.map(post => <li key={post._id}>{post.title}</li>)}
      </ul>
      <div>
        {Array.from({ length: totalPages }, (_, i) => (
          <button key={i} onClick={() => setPage(i + 1)}>
            {i + 1}
          </button>
        ))}
      </div>
    </div>
  );
}

export default PostList;

Real-World Tips

  • Always use server-side pagination for large datasets.
  • Return total count from backend to calculate total pages.
  • Consider adding filters or search alongside pagination for better UX.

Related Reading

If you’re working on a full stack app, you might also like our post: How to Handle File Uploads in MERN Stack with Multer.

Tools & Resources

Conclusion

Pagination is a crucial skill for creating efficient, user-friendly applications. With MongoDB handling the data and React rendering it smartly, you can scale your UI without sacrificing performance.

Try adding pagination to your next project and see how much smoother your app runs. 🚀

Comment your thoughts below and share your own tips!

💖

Enjoyed the Post?

If my blog helped you, please consider supporting me!

Support Me 💖

Post a Comment

0 Comments

Hi Everyone, please do not spam in comments.

Post a Comment (0)

Made with Love by

Welcome to Code Journey with Aamir – your one-stop hub for full-stack development tutorials, projec…