This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: tanstack-virtual-dynamic-measurement-and-containment

TanStack Virtual 3.0 Dynamic Measurement, Scroll Containment, and DOM Saturation Guardrails

Enforces deterministic element measurement, ref-bound layout stabilization, and multi-dimensional windowing containment for TanStack Virtual 3.0. Prevents catastrophic layout thrashing, infinite measurement oscillation loops, and DOM node saturation in high-density data tables.

Prohibited Anti-Pattern: Layout Thrashing, Infinite Resize Loops, and Memory Exhaustion via Naive Dynamic Measurement and Unbounded Column Rendering

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: TanStack Virtual 3.0 Dynamic Measurement, Scroll Containment, and DOM Saturation Guardrails - Enforces deterministic element measurement, ref-bound layout stabilization, and multi-dimensional windowing containment for TanStack Virtual 3.0. Prevents catastrophic layout thrashing, infinite measurement oscillation loops, and DOM node saturation in high-density data tables.
globs: src/**/*.{ts,tsx}, app/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/tanstack-virtual-dynamic-measurement-and-containment"
---

# TanStack Virtual 3.0 Dynamic Measurement, Scroll Containment, and DOM Saturation Guardrails

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Layout Thrashing, Infinite Resize Loops, and Memory Exhaustion via Naive Dynamic Measurement and Unbounded Column Rendering

## System Constraints
You are a Principal Software Architect enforcing zero-overhead virtualization using TanStack Virtual 3.0. You must ensure all virtualized containers implement deterministic size estimation, clean element measurement attachment via dataset indices, bounded overscan, GPU-accelerated coordinate transformations, and dual-axis windowing whenever cell counts threaten DOM budget limits.

## Strict Guidelines
- Engineers MUST ALWAYS attach `ref={virtualizer.measureElement}` to the rendered virtual element and define `data-index={virtualRow.index}` on that exact same DOM node when dynamic sizing is enabled.
- Engineers MUST ALWAYS provide a stable, deterministic `getItemKey: (index: number) => Key` callback mapping to a unique entity identifier instead of relying on default array index keys.
- Engineers MUST NOT mutate or recalculate `estimateSize` dynamically within render phases; `estimateSize` MUST be a stable, pure function returning a realistic median default height/width.
- Engineers MUST position virtual items using CSS hardware-accelerated transforms (`transform: translateY(${virtualRow.start}px)`) or CSS grid line indices, and NEVER use layout-triggering properties like `top`, `margin-top`, or dynamic padding spacers for individual items.
- Engineers MUST ALWAYS supply `scrollMargin: offsetRef.current?.offsetTop ?? 0` when the scroll viewport contains preceding sibling elements (such as sticky headers, filter bars, or banners) to prevent translation drift.
- Components NEVER render more than 30 total columns without implementing 2D dual-axis virtualization (`useVirtualizer` for rows AND columns); naively mapping unbounded cells inside a virtualized row violates DOM saturation budgets ($O(R \times C)$ node explosion).
- Engineers MUST keep `overscan` bounded strictly between 2 and 8 items to prevent redundant paint invalidations and layout recalibration overhead during high-velocity fling scrolls.

## Bad vs Good Implementations
### Dynamic Height Virtualization with Proper Ref Measurement and Key Stabilization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using array index as key invalidates DOM reusability on list shifts. Hardcoding `top` forces style recalculation and layout thrashing. Without `ref={virtualizer.measureElement}` and `data-index`, dynamic multiline text overflows or collapses without TanStack recalculating item offsets, causing visual overlap.
```typescript
import React from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';

interface RowItem {
  id: string;
  description: string;
}

export const BadVirtualList: React.FC<{ items: RowItem[] }> = ({ items }) => {
  const parentRef = React.useRef<HTMLDivElement>(null);

  const virtualizer = useVirtualizer({
    count: items.length,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 50, // Static estimate without dynamic measurement support
    overscan: 25, // Excessive overscan: saturates DOM during fast scroll
  });

  return (
    <div ref={parentRef} style={{ height: '500px', overflow: 'auto' }}>
      <div style={{ height: `${virtualizer.getTotalSize()}px`, position: 'relative' }}>
        {virtualizer.getVirtualItems().map((virtualRow) => {
          const item = items[virtualRow.index];
          return (
            // ANTI-PATTERN: Missing stable key, missing data-index attribute,
            // uses inline layout top property causing continuous browser reflows,
            // and fails to bind measureElement ref.
            <div
              key={virtualRow.index}
              style={{
                position: 'absolute',
                top: `${virtualRow.start}px`,
                width: '100%'
              }}
            >
              <h3>{item.id}</h3>
              <p>{item.description}</p>
            </div>
          );
        })}
      </div>
    </div>
  );
};
```

#### Production Standard (Correct)
> **Standard**: Employs `getItemKey` with domain UUIDs to preserve element identity across mutations. Attaches `measureElement` and `data-index` to allow automated ResizeObserver tracking without infinite loops. Uses `contain: strict` on the viewport and GPU-composited `transform: translateY()` to eliminate layout thrashing.
```typescript
import React from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';

interface RowItem {
  id: string;
  description: string;
}

export const OptimizedVirtualList: React.FC<{ items: RowItem[] }> = ({ items }) => {
  const parentRef = React.useRef<HTMLDivElement>(null);

  const getItemKey = React.useCallback(
    (index: number) => items[index]?.id ?? index,
    [items]
  );

  const virtualizer = useVirtualizer({
    count: items.length,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 72, // Realistic median estimate based on typical typography
    getItemKey,
    overscan: 5, // Bounded buffer balance between blank space and DOM pressure
  });

  return (
    <div
      ref={parentRef}
      role="region"
      aria-label="Dynamic Content Viewport"
      style={{ height: '500px', overflowY: 'auto', contain: 'strict' }}
    >
      <div
        style={{
          height: `${virtualizer.getTotalSize()}px`,
          width: '100%',
          position: 'relative',
        }}
      >
        {virtualizer.getVirtualItems().map((virtualRow) => {
          const item = items[virtualRow.index];
          return (
            <div
              key={virtualRow.key}
              ref={virtualizer.measureElement}
              data-index={virtualRow.index}
              style={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                transform: `translateY(${virtualRow.start}px)`,
                willChange: 'transform',
              }}
            >
              <h3 style={{ margin: 0 }}>{item.id}</h3>
              <p style={{ margin: 0 }}>{item.description}</p>
            </div>
          );
        })}
      </div>
    </div>
  );
};
```

### Scroll Margin Containment with Preceding Sticky Header

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Because `scrollRef` encapsulates an 80px toolbar before the virtual canvas, the viewport's scrollTop is offset by 80px. Without configuring `scrollMargin`, the virtualizer calculates item visibility assuming the canvas starts at scrollTop 0, producing blank render gaps and jittery jump scrolling.
```typescript
import React from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';

export const MisalignedVirtualContainer: React.FC<{ rows: string[] }> = ({ rows }) => {
  const scrollRef = React.useRef<HTMLDivElement>(null);

  // ANTI-PATTERN: Ignores preceding DOM siblings. The virtualizer computes
  // scroll offsets starting from 0, ignoring the 80px toolbar above the list.
  // As a result, items pop in late and scroll positioning is offset by 80px.
  const virtualizer = useVirtualizer({
    count: rows.length,
    getScrollElement: () => scrollRef.current,
    estimateSize: () => 40,
  });

  return (
    <div ref={scrollRef} style={{ height: '600px', overflow: 'auto' }}>
      <div style={{ height: '80px', background: '#ccc' }}>Pinned Toolbar Filter</div>
      <div style={{ height: `${virtualizer.getTotalSize()}px`, position: 'relative' }}>
        {virtualizer.getVirtualItems().map((virtualRow) => (
          <div
            key={virtualRow.index}
            style={{
              position: 'absolute',
              top: 0,
              transform: `translateY(${virtualRow.start}px)`,
            }}
          >
            {rows[virtualRow.index]}
          </div>
        ))}
      </div>
    </div>
  );
};
```

#### Production Standard (Correct)
> **Standard**: Defines `scrollMargin` using the exact `offsetTop` of the inner canvas ref relative to the viewport. Normalizes element translation by subtracting `virtualizer.options.scrollMargin`, ensuring absolute synchronization between native scroll position and item visibility thresholds.
```typescript
import React from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';

export const OffsetContainedVirtualList: React.FC<{ rows: string[] }> = ({ rows }) => {
  const scrollRef = React.useRef<HTMLDivElement>(null);
  const listContainerRef = React.useRef<HTMLDivElement>(null);

  const virtualizer = useVirtualizer({
    count: rows.length,
    getScrollElement: () => scrollRef.current,
    estimateSize: () => 40,
    getItemKey: (index) => `row-${index}`,
    // Correctly informs the virtualizer of preceding DOM layout displacement
    scrollMargin: listContainerRef.current?.offsetTop ?? 0,
  });

  return (
    <div ref={scrollRef} style={{ height: '600px', overflowY: 'auto' }}>
      <div style={{ height: '80px', background: '#f4f4f4' }}>Pinned Toolbar Filter</div>
      <div
        ref={listContainerRef}
        style={{
          height: `${virtualizer.getTotalSize()}px`,
          width: '100%',
          position: 'relative',
        }}
      >
        {virtualizer.getVirtualItems().map((virtualRow) => (
          <div
            key={virtualRow.key}
            ref={virtualizer.measureElement}
            data-index={virtualRow.index}
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              width: '100%',
              // Offset start using virtualRow.start - virtualizer.options.scrollMargin
              transform: `translateY(${virtualRow.start - virtualizer.options.scrollMargin}px)`,
            }}
          >
            {rows[virtualRow.index]}
          </div>
        ))}
      </div>
    </div>
  );
};
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: TanStack Virtual 3.0 Dynamic Measurement, Scroll Containment, and DOM Saturation Guardrails

TanStack Virtual 3.0 Dynamic Measurement, Scroll Containment, and DOM Saturation Guardrails defines an industrial-grade behavioral standard for frontend engineering. Enforces deterministic element measurement, ref-bound layout stabilization, and multi-dimensional windowing containment for TanStack Virtual 3.0. Prevents catastrophic layout thrashing, infinite measurement oscillation loops, and DOM node saturation in high-density data tables. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Layout Thrashing, Infinite Resize Loops, and Memory Exhaustion via Naive Dynamic Measurement and Unbounded Column Rendering Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftLayout Thrashing, Infinite Resize Loops, and Memory Exhaustion via Naive Dynamic Measurement and Unbounded Column RenderingCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS attach `ref={virtualizer.measureElement}` to the rendered virtual element and define `data-index={virtualRow.index}` on that exact same DOM node when dynamic sizing is enabled.

Engineers MUST ALWAYS attach `ref={virtualizer.measureElement}` to the rendered virtual element and define `data-index={virtualRow.index}` on that exact same DOM node when dynamic sizing is enabled.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST ALWAYS provide a stable, deterministic `getItemKey

Engineers MUST ALWAYS provide a stable, deterministic `getItemKey: (index: number) => Key` callback mapping to a unique entity identifier instead of relying on default array index keys.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Engineers MUST NOT mutate or recalculate `estimateSize` dynamically within render phases

Engineers MUST NOT mutate or recalculate `estimateSize` dynamically within render phases; `estimateSize` MUST be a stable, pure function returning a realistic median default height/width.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Engineers MUST position virtual items using CSS hardware-accelerated transforms (`transform

Engineers MUST position virtual items using CSS hardware-accelerated transforms (`transform: translateY(${virtualRow.start}px)`) or CSS grid line indices, and NEVER use layout-triggering properties like `top`, `margin-top`, or dynamic padding spacers for individual items.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Engineers MUST ALWAYS supply `scrollMargin

Engineers MUST ALWAYS supply `scrollMargin: offsetRef.current?.offsetTop ?? 0` when the scroll viewport contains preceding sibling elements (such as sticky headers, filter bars, or banners) to prevent translation drift.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

Components NEVER render more than 30 total columns without implementing 2D dual-axis virtualization (`useVirtualizer` for rows AND columns)

Components NEVER render more than 30 total columns without implementing 2D dual-axis virtualization (`useVirtualizer` for rows AND columns); naively mapping unbounded cells inside a virtualized row violates DOM saturation budgets ($O(R \times C)$ node explosion).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
7

Engineers MUST keep `overscan` bounded strictly between 2 and 8 items to prevent redundant paint invalidations and layout recalibration overhead during high-velocity fling scrolls.

Engineers MUST keep `overscan` bounded strictly between 2 and 8 items to prevent redundant paint invalidations and layout recalibration overhead during high-velocity fling scrolls.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is TanStack Virtual 3.0 Dynamic Measurement, Scroll Containment, and DOM Saturation Guardrails critical for AI coding assistants?

Enforces deterministic element measurement, ref-bound layout stabilization, and multi-dimensional windowing containment for TanStack Virtual 3.0. Prevents catastrophic layout thrashing, infinite measurement oscillation loops, and DOM node saturation in high-density data tables. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Layout Thrashing, Infinite Resize Loops, and Memory Exhaustion via Naive Dynamic Measurement and Unbounded Column Rendering) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related FRONTEND Rules

View all rules →
frontend
119

SolidStart 1.0 Server Functions & Async Boundaries Production Standard

SolidStart 1.0 relies on the Vinxi bundler to split `server$` closures into independent HTTP POST RPC endpoints. Direct lexical closure over client signals within `server$` scopes or failure to demarcate async boundaries with `<Suspense>` causes silent serialization failures, client-bundle secret leaks, and SSR hydration mismatches. Enforcing strict parameter passing, runtime input validation, and Solid async primitives maintains security and fine-grained reactivity across network boundaries.

frontend
119

Astro 5 Actions & Content Layer Production Standard

Enforces strict type safety and architectural correctness for Astro 5 Server Actions and the zero-waterfall Content Layer API. Prevents runtime contract mismatches, hydration mismatches, and unhandled mutation exceptions across dynamic and prerendered boundaries. Failure to follow these patterns leads to silent data fetching waterfalls, build-time cache corruptions, and unhandled server action exceptions.

frontend
51

Nuxt 4 Nitro Server Engine & Shared Directory Production Standard

Nuxt 4 enforces strict boundary segregation between client UI in the app/ directory, backend endpoints in server/, and universal contracts in shared/. Violating cross-boundary isolation or maintaining module-scoped state in Nitro server handlers causes catastrophic cross-request data corruption and hydration mismatches under concurrent production traffic. Architects must enforce request-isolated H3 event contexts, universal serialization schemas, and strict path-alias boundaries.

1 Rule in Stack

TanStack