How infinite scroll works in chat apps and social feeds
A plain-English guide to infinite scroll: loading older chat messages without a jump, staying at the bottom, virtual lists and duplicate posts.
Scroll up in a chat app and older messages appear above the ones you were reading. Scroll down a social feed and more posts keep coming. Both are infinite scroll, but they're built differently, and each has a few problems that only show up once real people start using it.
This guide goes through those problems one at a time, with a picture for each. The code is plain browser JavaScript, with a little React, so it works whatever your backend is.
Two lists that grow in opposite directions
A feed starts at the top. When the reader gets near the end, you add more posts at the bottom. They go in below what's on screen, so nothing the reader is looking at moves. That's the easy case.
A chat starts at the bottom, on the newest message. When the reader scrolls up, you add older messages at the top, above what they're looking at. Most of the trouble in this guide comes from that: anything added above the screen pushes everything on the screen down.
Knowing when to load more
The old way is to listen for the scroll event and check the position each time. It works, but scroll events fire many times a second, and you end up doing that check constantly.
There's a simpler way. Put an empty element, a sentinel, at the end of the list where new content will arrive: at the bottom of a feed, or at the top of a chat. Then ask the browser to tell you when it comes into view. That's what IntersectionObserver does.
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting && !isLoading && hasMore) {
loadNextPage();
}
},
{
root: listElement, // watch inside the list, not the whole page
rootMargin: "400px 0px", // start loading 400px before the edge
},
);
observer.observe(sentinelElement);
The rootMargin makes the next page start loading a little before the reader reaches the end, so most of the time they never see a spinner.
The two checks in the callback matter. isLoading stops a second request going out while the first one is still on its way, because the sentinel can stay in view and fire again. hasMore stops the requests once there's nothing left. A simple way to know: if you asked for 20 items and got fewer back, you've reached the end.
Loading older messages without a jump
Say the reader is looking at messages 21 to 25 and scrolls to the top. You load messages 1 to 20 and put them above. The list is now much taller, but the browser keeps the scroll position where it was, counted from the top. So suddenly the reader is looking at messages 1 to 5 and has lost their place.
The fix is to measure the list's height before you add the messages, then move the scroll position down by however much it grew:
const heightBefore = list.scrollHeight;
addOlderMessages(); // render them
// then, before the browser paints:
list.scrollTop += list.scrollHeight - heightBefore;
In React, do the second part in useLayoutEffect. It runs after the new messages are in the page but before the screen updates, so the reader never sees the jump.
Browsers have a built-in version of this called scroll anchoring (the overflow-anchor property). It isn't enough on its own: Safari doesn't support it. If you correct the position yourself, turn the built-in one off with overflow-anchor: none on the list, so the browser and your code don't both move it.
You'll also see a different trick: flip the list with flex-direction: column-reverse. The scroll position is then counted from the bottom, so content added at the top doesn't move anything. It's neat, but scrollTop becomes 0 at the bottom and negative as you scroll up. Any code that reads the scroll position has to know the list is flipped.
Staying at the bottom, but only when the reader is there
A new message arrives. Should the chat scroll down to show it? It depends on where the reader is.
If they're at the bottom, yes. If they've scrolled up to read something from yesterday, no. Pulling them down would be annoying. Show a small "New messages" button instead and let them decide.
So you need to know whether the reader is near the bottom. "Exactly at the bottom" is too strict, because a pixel of rounding makes it false, so allow some room, around 100 to 200 pixels:
function isNearBottom(list, margin = 150) {
const distance = list.scrollHeight - list.scrollTop - list.clientHeight;
return distance < margin;
}
// Check BEFORE adding the message: afterwards it has already
// pushed the reader away from the bottom.
const shouldFollow = isNearBottom(list) || message.isMine;
addMessage(message);
if (shouldFollow) {
list.scrollTop = list.scrollHeight;
}
Always follow the reader's own messages. When you send something, you expect to see it.
Images cause one more problem. A photo message arrives, you scroll to the bottom, then the photo finishes loading and makes the list taller, so you're no longer at the bottom. The best fix is to know the image's size before it loads (send width and height with the message) and reserve that space. If you can't, watch the list with a ResizeObserver for a moment after scrolling, and scroll again when it grows.
Jumping to an old message
Search results and replies ("show me the message this answers") need to scroll to a message that might be hundreds of messages back and not loaded yet.
Loading one page after another until it turns up is slow. If you store messages with a timestamp, you can do it in one step. Count how many messages are newer than the target, then load that many plus a few more, so there's some context above it. Once it's on the page, scroll it to the middle of the screen and highlight it for a second, so the eye can find it.
const newerCount = await countMessagesNewerThan(roomId, target.timestamp);
await loadNewestMessages(newerCount + 20);
document
.querySelector(`[data-message-id="${target.id}"]`)
.scrollIntoView({ block: "center", behavior: "smooth" });
If the messages live in IndexedDB with an index on room and timestamp, that count reads only the index. It doesn't need to load the messages in between.
Keeping long lists fast
Every message or post you load becomes elements on the page. A few hundred are fine. A few thousand, with images and video, and scrolling starts to stutter.
Virtualization (also called windowing) fixes that. Only the items on screen, plus a few on each side, are actually rendered. The rest of the list is replaced by two empty spacers with the right height, so the scrollbar still looks and feels normal.
Libraries such as react-virtuoso and TanStack Virtual do the work. The hard part is that they need to know how tall each item is, and in a chat or a feed every item is different: a one-word reply, a long paragraph, a photo, a poll. They start with an estimate and measure each item as it renders. A good estimate means less jumping, so set it near your typical item, not your smallest one.
Chats are harder still, because most virtual lists expect items to be added at the end. Adding at the start needs special support. In react-virtuoso that's the firstItemIndex prop, which you lower by the number of items you add.
If a virtual list is more than you need, CSS can help. content-visibility: auto lets the browser skip rendering items that are off screen. Pair it with contain-intrinsic-size, so skipped items keep a sensible height and the scrollbar doesn't jump (web.dev has the details).
.message {
content-visibility: auto;
contain-intrinsic-size: auto 80px; /* placeholder height until it has rendered once */
}
Why feeds show the same post twice
Most APIs start with page numbers: "give me page 2, 10 posts per page". The server skips the first 10 and returns the next 10.
The trouble is that the list changes while the reader scrolls. If someone publishes a post after page 1 has loaded, everything shifts down by one. Page 2 now starts with the last post of page 1, and the reader sees it twice. If a post is deleted, everything shifts up instead, one post is skipped, and the reader never sees it.
You can hide duplicates on the client by remembering which IDs you've already shown:
const shownIds = new Set(posts.map((post) => post.id));
const newPosts = nextPage.filter((post) => !shownIds.has(post.id));
setPosts([...posts, ...newPosts]);
Skipped posts can't be fixed that way, because the client never knew they existed. The real fix is on the server: cursor pagination. Instead of "page 2", the client asks for "the 10 posts after this one", passing the ID or timestamp of the last post it has. A new post at the top doesn't change what comes after a given post, so nothing repeats and nothing is skipped. Slack wrote about moving its API from offsets to cursors.
Full-screen video feeds
Short-video feeds, where one video fills the screen and you swipe to the next, are a special case. They're easier in one way: every item is the same height. You don't have to measure anything. The current video is the scroll position divided by the item height, rounded.
CSS scroll snap makes each swipe land on exactly one video:
.feed {
overflow-y: auto;
scroll-snap-type: y mandatory;
}
.video {
height: 100dvh;
scroll-snap-align: start;
scroll-snap-stop: always; /* a fast swipe can't fly past several videos */
}
Video is heavy, so only the current one should play, and ideally only the current one should have a video element at all. When a video leaves the screen, pause it, remove its src and call load(). That tells the browser it can let go of the video data.
You'll see this error a lot: "The play() request was interrupted by a call to pause()". It happens when someone swipes past a video before it starts. play() returns a promise that rejects in that case, and it's harmless. Catch it and ignore just that one:
video.play().catch((error) => {
if (error.name !== "AbortError") console.error(error);
});
A checklist
- Use a sentinel and
IntersectionObserverto know when to load, not a check on every scroll event. - Don't start a second request while one is in flight, and stop when the server runs out.
- When you add content above the reader, restore their scroll position before the screen updates.
- Follow new messages only when the reader is near the bottom, or sent the message.
- Reserve space for images, so the list doesn't change height after it renders.
- Once lists get long, virtualize them or use
content-visibility. - Drop duplicates by ID, and use cursor pagination on the server if you can.
- For video, play only the current item and release the others.