Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 4 min read

Your Per-Item ResizeObserver Is a Layout Feedback Loop

Every virtualized list with variable-height rows eventually meets the same bug: you add a ResizeObserver to each row so you can measure it, write the measured height back into your layout state, and the page starts fight

Every virtualized list with variable-height rows eventually meets the same bug: you add a ResizeObserver to each row so you can measure it, write the measured height back into your layout state, and the page starts fighting the user's scroll. GitHub's diff-surface rebuild hit exactly this, and their fix generalizes to any large list. By the end you will know how to detect the feedback loop, how to batch measurements, and how to anchor height corrections so they don't move content under the cursor.

The feedback loop, concretely

Here is the pattern. You virtualize a list, so each row needs a measured height. You attach a ResizeObserver per row and write the height into your virtualizer's state:

// The trap: measurement triggers layout, layout triggers measurement
const observer = new ResizeObserver((entries) => {
  for (const entry of entries) {
    const row = rowsById.get(entry.target.dataset.id);
    if (row) {
      virtualizer.setSize(row.id, entry.contentRect.height);
      // setSize invalidates layout -> rows re-render -> sizes change again
    }
  }
});

rows.forEach((el) => observer.observe(el));

This works fine at fifty rows and degrades at ten thousand. Every height write invalidates layout, which re-renders rows, which fires observers again. The cost grows with every mounted block, and the user sees it as jank while scrolling.

Separate the deterministic from the dynamic

GitHub's diff surface contains two things that behave differently. Code rows have a fixed height for a given font size, so you can compute their geometry up front and never measure them. Comments, reply composers, and collapsible sections do not. Their height depends on content, open state, and container width.

Split them:

total height = fixed-height items (computed)
             + Ξ£ dynamic block heights (measured)
             + scroll padding

Most lists have this structure once you look for it. A chat transcript has message text (variable) plus one-line system entries (fixed). A settings page has sections (variable) plus uniform rows (fixed). Compute everything you can; measure only what you must.

Key the dynamic blocks by identity, not pixel position, and track a fingerprint of everything that changes height: content, open state, and measured width. You only need to re-measure when the fingerprint changes.

Batch measurements on idle

One observer per block, each writing synchronously, is the trap. Keep the observers but demote them to flagging. Collect dirty flags, then drain them in one batched pass, gated on requestIdleCallback:

const dirty = new Set();

new ResizeObserver((entries) => {
  for (const e of entries) dirty.add(e.target.dataset.id);
  scheduleMeasure();
});

function scheduleMeasure() {
  if (scheduled) return;
  scheduled = true;
  requestIdleCallback(() => {
    scheduled = false;
    const targets = [...dirty].filter(withinViewportRange);
    measureAll(targets); // one layout pass, not one per block
  });
}

Two details matter. First, scope the pass to blocks near the viewport; measuring everything on the page defeats the point. Second, apply all corrections in a single pass so the layout invalidates once instead of once per row.

Anchor corrections to what the reader sees

A batched measurement still has a cost: heights change after you have already rendered. If you absorb those changes into the top of the list, content jumps under the reader's cursor. That jump is the classic symptom that makes people distrust virtualization.

Instead, anchor the correction. When a block above the viewport changes height, adjust the scroll offset by the same amount. When a block below changes, let the layout absorb it. The code on the screen stays put; the math under it changes.

function applyHeights(corrections, viewportTop) {
  let aboveDelta = 0;
  let belowDelta = 0;
  for (const { id, delta } of corrections) {
    heights.set(id, delta + heights.get(id));
    if (blockEnd(id) <= viewportTop) aboveDelta += delta;
    else belowDelta += delta;
  }
  if (aboveDelta !== 0) scrollTop += aboveDelta;
}

Keep one synchronous escape hatch

Some interactions cannot tolerate a delayed correction. When a user toggles a collapsible section or opens a reply composer, the content below must move in the same frame or it looks broken. GitHub keeps a frame-synchronous path for exactly those cases: the toggle writes its height immediately, everything else waits for the idle pass.

The rule is easy to state: user-initiated dimension changes are synchronous, passive measurement is batched. If you find yourself making exceptions for rendering, you have reintroduced the loop.

Test the invariant, not the vibe

Layout regressions are silent. The fix that survives code review today is the one that regresses next quarter. Encode the invariant as a CI budget against a synthetic fixture with thousands of variable-height rows:

  • Total computed height matches a golden value for the fixture.
  • Scroll-anchored corrections never shift content under a scripted scroll position.
  • A scripted scroll of the whole fixture fires at most N batched measurement passes.

GitHub pairs this with an automated driver that runs the real app through a scripted flow, cold and warm, and reads an on-disk log so an agent can spot regressions without anyone at the keyboard. You can start smaller: one fixture, one assertion, in CI.

Key takeaways

  • One ResizeObserver per item writing heights back into layout is a feedback loop whose cost scales with mounted item count.
  • Split your list into fixed-height items you compute and variable-height blocks you measure, keyed by identity plus a fingerprint of content, open state, and width.
  • Batch measurements into a single idle-gated pass scoped near the viewport, and anchor corrections so content under the reader never moves.
  • User-initiated toggles get a synchronous correction; passive re-measurement does not.
  • Turn the invariant into a CI budget on a synthetic large-list fixture, because layout regressions will not show up in any test you wrote for behavior.

Source

GitHub Rebuilds the Copilot App's Diff Surface to Open Million-Line Pull Requests Without Jank -- I added the generalized pattern, working JavaScript for the batching and scroll-anchoring, and the testing strategy the source only gestures at.

Support this work

These write-ups are researched and published with no paywall, sponsor, or tracking. If one saved you an afternoon, a small tip keeps them coming.

USDT, USDC or USDD Β· TRC-20 (Tron)

TFTNsfyomKrnUutRjBTGVULp19ByW29KbY
πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.