🚨 Why Your Infinite Scroll is Laggy in MERN (and How to Fix It)
Most devs build pagination in MongoDB like this:
const posts = await Post.find()
.sort({ createdAt: -1 })
.skip(page * limit)
.limit(limit);
It works at first. But once your database grows, it breaks:
– Mongo still scans all skipped docs → queries get slower
– Inserts shift items → users see duplicates or miss posts
The fix? Cursor-based pagination. Use createdAt (or _id) as a cursor instead of skip().
const posts = await Post.find({
createdAt: {
$lt: lastPostDate }
})
.sort({ createdAt: -1 })
.limit(limit);
On the frontend (React), just pass the last item’s createdAt back when fetching more:
const loadMore = async () => {
const res = await fetch(/api/posts?cursor=${lastDate});
const newPosts = await res.json();
setPosts([…posts, …newPosts]);
};
Pro tip: Index your createdAt field for speed.
PostSchema.index({ createdAt: -1 });
When you switch to cursor-based pagination:
✅ Queries stay fast even with millions of records
✅ No duplicates, no missing items
✅ Smooth infinite scroll UX your users will love
Most MERN performance issues aren’t about servers or hosting.
They’re about how you query Mongo.
Fix this, and your app will feel instantly better.
#MERN #SoftwareEngineer #BackendProgramming #MongoDB #Pagination