[BUG] Preserve scroll position when prepending variable-height items before initial scroll
Author: dqbdCreated May 13, 2026Updated May 13, 2026
Labelsbug
Describe the bug
When prepending variable-height items (and updating firstItemIndex accordingly) before any user scroll interaction happens, the content shifts unexpectedly after the prepend operation.
Reproduction
Sandbox: https://codesandbox.io/p/sandbox/dh9hgl
import { useMemo, useRef, useState } from 'react'
import { faker } from '@faker-js/faker'
import { Virtuoso, type Components } from 'react-virtuoso'
const generated: ReturnType<typeof user>[] = []
export function toggleBg(index: number) {
return index % 2 ? '#f5f5f5' : 'white'
}
export function user(index = 0) {
const firstName = faker.name.firstName()
const lastName = faker.name.lastName()
return {
bgColor: toggleBg(index),
description: faker.lorem.sentence(10),
height: 60 + Math.floor(Math.abs(Math.sin(index * 7919)) * 400),
index: index + 1,
initials: `${firstName.substring(0, 1)}${lastName.substring(0, 1)}`,
jobTitle: faker.name.jobTitle(),
name: `${firstName} ${lastName}`,
}
}
export const getUser = (index: number) => {
if (generated[index] === undefined) {
generated[index] = user(index)
}
return generated[index]
}
function LoadMore(props: { direction: 'up' | 'down'; onLoadMore: () => void }) {
return (
<div>
<button onClick={props.onLoadMore}>{props.direction === 'up' ? 'Load Older' : 'Load Newer'}</button>
</div>
)
}
const BATCH_SIZE = 5
const START_INDEX = 10000
const INITIAL_ITEM_COUNT = 10
const initialEndIndex = START_INDEX + INITIAL_ITEM_COUNT
function Item({ user }: { user: ReturnType<typeof getUser> }) {
return (
<div style={{ backgroundColor: user.bgColor, height: user.height, padding: '1rem 0.5rem' }}>
<h4>
{user.index}. {user.name}
</h4>
<div style={{ marginTop: '0.5rem' }}>{user.description}</div>
<div style={{ color: '#999', fontSize: '0.75rem', marginTop: '0.25rem' }}>height: {user.height}px</div>
</div>
)
}
export function Example() {
const [firstItemIndex, setFirstItemIndex] = useState(START_INDEX)
const [users, setUsers] = useState(() => generateUsers(INITIAL_ITEM_COUNT, START_INDEX))
const endIndexRef = useRef(initialEndIndex)
type Data = ReturnType<typeof getUser>
interface Context {
loadMore: (direction: 'up' | 'down') => void
}
const context = useMemo((): Context => {
return {
loadMore: (direction: 'up' | 'down') => {
if (direction === 'up') {
console.log('prependItems doing')
const nextFirstItemIndex = firstItemIndex - BATCH_SIZE
setTimeout(() => {
setFirstItemIndex(nextFirstItemIndex)
setUsers((prev) => [...generateUsers(BATCH_SIZE, nextFirstItemIndex), ...prev])
}, 300)
} else {
console.log('appendItems doing')
const startIndex = endIndexRef.current
setTimeout(() => {
endIndexRef.current = startIndex + BATCH_SIZE
setUsers((prev) => [...prev, ...generateUsers(BATCH_SIZE, startIndex)])
}, 300)
}
},
}
}, [firstItemIndex])
const components = useMemo((): Components<Data, Context> => {
return {
Header: ({ context }) => <LoadMore direction="up" onLoadMore={() => context.loadMore('up')} />,
Footer: ({ context }) => <LoadMore direction="down" onLoadMore={() => context.loadMore('down')} />,
}
}, [])
const scrollerRef = useRef<HTMLDivElement | null>(null)
return (
<Virtuoso<Data, Context>
scrollerRef={(ref) => {
scrollerRef.current = ref as HTMLDivElement | null
}}
data={users}
context={context}
components={components}
firstItemIndex={firstItemIndex}
initialTopMostItemIndex={0}
style={{ height: 800 }}
increaseViewportBy={{ bottom: 1600, top: 0 }}
itemContent={(_, user) => <Item user={user} />}
/>
)
}
function generateUsers(length: number, startIndex = 0) {
return Array.from({ length }).map((_, i) => getUser(i + startIndex))
}To Reproduce
Steps to reproduce the behavior:
- Click on "Load Older" before scrolling the list
- Observe shift in content (see attached video)
The issue does not reproduce when user scrolls upwards before prepending.
Expected behavior
When "Load Older" is clicked, the scroll position stays consistent, even though no scroll event happened.
Screenshots
https://github.com/user-attachments/assets/5fdb6e9d-392b-44b1-b054-20b5f5aae6eb
Desktop (please complete the following information):
- OS: macOS
- Browser: Chromium 148.0.778.96 (arm64)
Additional context
Attempted a fix at #1397, which resolves the issue for me.
Source: petyosi/react-virtuoso