Question presented to candidate: "Our social feed has 10,000 posts and every post is a different height: short text, long text with a Show more button, some with a photo. We cannot know the heights before the browser renders them. Build a virtualized feed that only mounts what is on screen, keeps the scrollbar roughly right, and does not make the post you are reading jump when posts above it get measured."
Requirements:
- Load 10,000 posts from a simulated API, then render them in a 600px scroll box with only the visible posts (plus 3 of overscan) mounted.
- Use an estimated height (120px) for posts that have never been rendered, measure each mounted post, and cache the real height by post id.
- Find the first visible post from
scrollTopefficiently, without walking 10,000 heights on every scroll. - When a post above the viewport changes height (first measurement, an image, a font), keep the content under the reader still.
- Posts longer than 160 characters show a "Show more" toggle; expanding re-measures the post and pushes the ones below down.
- Use the ARIA feed pattern:
role="feed", articles witharia-posinsetandaria-setsize.
What a strong answer should cover:
- Why fixed-size maths fails, and the replacement: a prefix-sum array of offsets built from measured or estimated heights, searched with binary search.
- Measurement with
ResizeObserveron each mounted row (initial notification plus later changes), keyed by item id, using border-box size so padding is included. - Scroll anchoring: when a row above the first visible row changes by
delta, adddeltatoscrollTopbefore paint, and setoverflow-anchor: noneso the browser does not also correct. - Where the work runs (layout effect or post-render hook) so the correction happens before the user sees a frame.
- Trade-offs: estimate quality versus scrollbar jitter, measuring cost, and what libraries (react-window 2 dynamic heights, TanStack Virtual, react-virtuoso) do.
Clarifying questions expected:
- "Can posts change height after they render, for example images loading or Show more?"
- "Does the feed grow at the top (new posts) or only at the bottom?"
- "Do we need jump-to-post, and how exact must it be for unmeasured posts?"
Code / implementation expected: Yes. A feed component with a height cache, prefix sums, binary search, a measuring row and the anchoring correction. A brief mention of library equivalents is enough.