Below is a “recipe” you can reuse in ANY modern front-end stack (React, Vue, Svelte, Solid, etc.) to render an arbitrarily deep tree and keep it snappy with virtualisation.
The idea in short:
- Keep your data in a real tree.
- Keep your UI in a FLAT “visible-nodes” array (depth-first, expand/collapse aware).
- Hand the flat array to a list-virtualiser (react-window / vue-virtual-scroller / svelte-virtual).
- Draw each row with the proper left-padding (or whatever) that corresponds to its depth.
That’s it—recursion once when building the visible list, not when rendering.
- Example data structure
type Node = {
id: string;
label: string;
children?: Node[];
};
- Helper: flatten only the nodes that should be shown
function flattenVisible(nodes: Node[],
expanded: Set<string>,
depth = 0,
acc: { node: Node; depth: number }[] = []) {
for (const n of nodes) {
acc.push({ node: n, depth }); // always push the node itself
if (expanded.has(n.id) && n.children) {
flattenVisible(n.children, expanded, depth + 1, acc); // recurse
}
}
return acc;
}
- React implementation (≈30 lines) 💡
import { FixedSizeList as List, ListChildComponentProps } from 'react-window';
import { useMemo, useState } from 'react';
// top-level tree component ----------------------------------
export default function VirtualTree({ data }: { data: Node[] }) {
const [expanded, setExpanded] = useState<Set<string>>(new Set());
// build the flat visible list whenever data OR expansion changes
const visible = useMemo(
() => flattenVisible(data, expanded),
[data, expanded]
);
// renderer for each row in the virtual list --------------
const Row = ({ index, style }: ListChildComponentProps) => {
const { node, depth } = visible[index];
const hasChildren = !!node.children?.length;
const isOpen = expanded.has(node.id);
function toggle() {
const next = new Set(expanded);
isOpen ? next.delete(node.id) : next.add(node.id);
setExpanded(next);
}
return (
<div style={{ ...style, paddingLeft: depth * 16, whiteSpace: 'nowrap' }}>
{hasChildren && (
<span onClick={toggle} style={{ cursor: 'pointer', marginRight: 4 }}>
{isOpen ? '▼' : '▶'}
</span>
)}
{node.label}
</div>
);
};
// the virtual list itself --------------------------------
return (
<List
height={400}
itemCount={visible.length}
itemSize={24}
width="100%"
>
{Row}
</List>
);
}
Key points:
• Only visible.length rows ever hit the DOM, no matter how huge the original tree.
• Expand/collapse is O(1) set updates + O(children) flatten, but still a fraction of full re-rendering.
• You’re free to swap FixedSizeList for VariableSizeList if rows vary in height.
- Vue (2/3) skeleton
<script setup lang="ts">
import { ref, computed } from 'vue';
import VirtualList from 'vue3-virtual-scroll-list'; // or vue-virtual-scroller
const props = defineProps<{ data: Node[] }>();
const expanded = ref<Set<string>>(new Set());
const visible = computed(() =>
flattenVisible(props.data, expanded.value)
);
function toggle(id: string) {
const s = new Set(expanded.value);
s.has(id) ? s.delete(id) : s.add(id);
expanded.value = s;
}
</script>
<template>
<VirtualList
:data-key="row => row.node.id"
:data-sources="visible"
:data-component="Row"
:keeps="30"
:estimate-size="24"
/>
</template>
<!-- Row component can be inlined or extracted -->
<script>
export default {
props: ['data'],
template: `
<div :style="{ paddingLeft: data.depth * 16 + 'px' }">
<span v-if="data.node.children?.length"
@click="$emit('toggle', data.node.id)">
{{ $parent.expanded.has(data.node.id) ? '▼' : '▶' }}
</span>
{{ data.node.label }}
</div>`
};
</script>
- Styling / UX sprinkles
• Use a monospace font and '│ ├─' ASCII art, or CSS borders + :before pseudo-elements, to draw actual tree lines.
• On hover, show quick-actions (add, delete, drag handle).
• Keep a selectedId in state to highlight the current node.
• For very wide trees consider a horizontal virtualiser instead.
- Why not simply nest components?
You can:
function RecursiveNode({ node }) {
const [open, setOpen] = useState(false);
return (
<div>
<div onClick={() => setOpen(!open)}>{node.label}</div>
{open && node.children?.map(c => (
<div key={c.id} style={{ paddingLeft: 16 }}>
<RecursiveNode node={c} />
</div>
))}
</div>
);
}
That’s great for ≤1k nodes. Past that, you’ll hit:
• Deep React/Vue component stacks (call stack, memory).
• Lots of DOM nodes (layout + paint time).
Virtualising the flattened list neatly sidesteps both issues.
- Libraries that already do this
React → react-vtree, react-arborist, @atlaskit/tree, react-sortable-tree.
Vue → vue3-easy-data-tree, vue-virtual-tree.
Svelte → svelte-tree-view, svelte-virtual-tree.
But rolling your own as shown above keeps bundle size tiny and API 100 % under your control.
Recap
• Store your data hierarchically.
• Store your UI rows flat and recompute on expand/collapse.
• Feed the rows to a list virtualiser.
• Indent according to depth and add a toggle caret.
Now you can render a 50 000-node tree and still scroll at 60 fps 🚀