Next.js Discord

Discord Forum

Need help keeping scroll position when loading older chat messages (TanStack Virtual + Next.js)

Unanswered
Pacific herring posted this in #help-forum
Open in Discord
Pacific herringOP
Hey everyone

I’m building a chat UI in Next.js (App Router) and I’m struggling with maintaining the scroll position when fetching older messages at the top.

I’m using @tanstack/react-virtual for virtualization and useInfiniteQuery from @tanstack/react-query to load messages.

The behavior I want is:
- When the user scrolls to the top, I fetch the previous page of messages
- The new messages prepend correctly
- But I want the scroll position to stay stable (so the user doesn’t feel a “jump”)

I’ve tried taking a scroll snapshot before fetching and restoring it after new messages render, but the timing is tricky because the virtualizer updates its measurements asynchronously.

Has anyone found a clean / idiomatic way to handle “infinite scroll from top” while keeping the scroll position stable using TanStack Virtual?

Any code examples, tips, or libraries that make this easier would be amazing 🙏

1 Reply

Dutch
show some video describes that behavior and problem