# Tree at scale (virtual + lazy)

SvTree scaling to 10,100 nodes via fixed-row virtualization (only ~15 rows in the DOM), plus a lazy-loading tree that fetches each folder’s children on first expand with a spinner. Keyboard, selection and cascading checkboxes intact.

Uses `@svgrid/grid` (MIT). Category: Layout. Live demo: https://svgrid.com/demos/324-tree-scale/

Install: `npm i @svgrid/grid` (Svelte 5).

## About this example

SvTree at scale in Svelte 5: a virtualized tree of 10,100 nodes where only about fifteen rows exist in the DOM through fixed-row windowing with virtual, height and rowHeight, and a lazy-loading tree that fetches each folder's children on first expand with a spinner. Keyboard navigation, selection and cascading checkboxes keep working in both.

SvTree at scale: a virtualized 10,000-node tree (only visible rows in the DOM) and a lazy-loading tree that fetches each folder's children on first expand. Both keep keyboard nav, selection and cascading checkboxes.

## Imports, features and API used

- Imports: `@svgrid/grid`

## Frequently asked questions

### How do I virtualize the tree?

Set virtual with a height for the scroll container and a rowHeight. The tree windows its flattened visible rows, so expanding a folder with thousands of children costs the same as a small one.

### How does lazy loading work?

Nodes are marked as having children not yet loaded; onToggle fetches them, shows a spinner row in the meantime and appends the result to the node, after which it behaves like a normal branch.

### Do checkboxes cascade across lazy nodes?

For loaded nodes, yes. A folder whose children are not loaded yet is checked as a unit and its children inherit the state when they arrive.

## Related documentation

- [SvTree](https://svgrid.com/docs/help/ui-components/sv-tree.md)

## Related articles

- [Saved Views - Persist Grid Layout and Filters](https://svgrid.com/blog/saved-views-persist-layout/) - Give users named, switchable snapshots of column order, sorting, filters, and grouping - persisted to localStorage or a server adapter - using SvGrid's createNamedViews API.
- [Building a Log Viewer for Large Logs in Svelte](https://svgrid.com/blog/log-viewer-large-logs/) - How to build a production-ready log viewer with SvGrid - virtualization for millions of lines, severity coloring, live tailing with scroll-lock, and server-side filtering.
- [Lazy-Loading Master-Detail Content in SvGrid](https://svgrid.com/blog/lazy-loading-master-detail-content/) - Fetch detail-panel data only when a row is expanded, cache the results, and cancel abandoned requests - keeping a large grid fast without paying for panels no one views.

## Source code (324-tree-scale.svelte)

```svelte
<script lang="ts">
  /**
   * SvTree at scale: a virtualized 10,000-node tree (only visible rows in the
   * DOM) and a lazy-loading tree that fetches each folder's children on first
   * expand. Both keep keyboard nav, selection and cascading checkboxes.
   */
  import { SvTree } from '@svgrid/grid'
  import type { SvTreeNode } from '@svgrid/grid'

  // ---- 10,000 nodes: 100 folders x 100 files -------------------------------
  const bigNodes: SvTreeNode[] = Array.from({ length: 100 }, (_, f) => ({
    id: `f${f}`,
    label: `Folder ${f + 1}`,
    children: Array.from({ length: 100 }, (_, i) => ({ id: `f${f}-${i}`, label: `File ${f + 1}.${i + 1}` })),
  }))
  const total = 100 + 100 * 100
  let selected = $state<string | null>('f0-0')
  let expanded = $state<string[]>(['f0'])

  // ---- Lazy loading: folders fetch children on first expand ----------------
  const lazyNodes: SvTreeNode[] = [
    { id: 'docs', label: 'Documents', lazy: true },
    { id: 'media', label: 'Media', lazy: true },
    { id: 'projects', label: 'Projects', lazy: true },
  ]
  let lazyExpanded = $state<string[]>([])
  let lazySelected = $state<string | null>(null)

  // Simulate a server round-trip (deterministic - no Math.random).
  function loadChildren(node: SvTreeNode): Promise<SvTreeNode[]> {
    return new Promise((resolve) =>
      setTimeout(() => {
        resolve(
          Array.from({ length: 5 }, (_, i) => ({
            id: `${node.id}-${i}`,
            label: `${node.label} item ${i + 1}`,
            // Nest one more lazy level to show it recurses.
            lazy: i === 0,
          })),
        )
      }, 650),
    )
  }
</script>

<div class="wrap">
  <header>
    <h2>Tree at scale</h2>
    <p>Two production patterns: a <strong>virtualized {total.toLocaleString()}-node</strong> tree, and a <strong>lazy-loading</strong> tree that fetches children on demand.</p>
  </header>

  <div class="cols">
    <section>
      <h3>Virtualized ({total.toLocaleString()} nodes)</h3>
      <SvTree
        nodes={bigNodes}
        {selected}
        expandedIds={expanded}
        virtual
        height={360}
        rowHeight={30}
        onSelect={(id) => (selected = id)}
        onToggle={(id, open) => (expanded = open ? [...expanded, id] : expanded.filter((e) => e !== id))}
      />
      <p class="note">Expand a few folders and scroll - only ~15 rows are ever in the DOM.</p>
    </section>

    <section>
      <h3>Lazy-loaded (fetch on expand)</h3>
      <SvTree
        nodes={lazyNodes}
        selected={lazySelected}
        expandedIds={lazyExpanded}
        {loadChildren}
        height={360}
        onSelect={(id) => (lazySelected = id)}
        onToggle={(id, open) => (lazyExpanded = open ? [...lazyExpanded, id] : lazyExpanded.filter((e) => e !== id))}
      />
      <p class="note">Each folder spins while it loads (~650ms), then reveals its children. The first child is itself lazy.</p>
    </section>
  </div>
</div>

<style>
  .wrap { padding: 20px; max-width: 720px; display: flex; flex-direction: column; gap: 18px; }
  header h2 { margin: 0 0 4px; font-size: 20px; font-weight: 700; }
  header p { margin: 0; color: var(--sg-muted, #64748b); font-size: 13.5px; line-height: 1.5; }
  .cols { display: flex; gap: 28px; flex-wrap: wrap; align-items: start; }
  section h3 { margin: 0 0 10px; font-size: 12px; text-transform: uppercase; letter-spacing: 0.03em; color: var(--sg-muted, #64748b); }
  .note { margin: 8px 0 0; font-size: 12px; color: var(--sg-muted, #94a3b8); max-width: 300px; line-height: 1.5; }
</style>
```

[View this example on GitHub](https://github.com/sv-grid/sv-grid/blob/main/examples/src/demos/324-tree-scale.svelte)
