Explicit Resource Management (using)
Problem
You create a virtualizer inside a function or block scope and want it destroyed automatically when the block exits — without a try/finally or a manual destroy() call.
Solution
ts
import { createVirtualizer } from '@vielzeug/virtualit';
function renderList(scrollEl: HTMLElement, rows: string[]) {
using virt = createVirtualizer(scrollEl, {
count: rows.length,
estimateSize: 36,
onChange: (virtualItems, totalSize) => {
// render...
},
});
// ... synchronous setup ...
} // virt.destroy() is called automatically herePitfalls
usingonly triggers[Symbol.dispose]when the declared variable goes out of scope. If you pass the virtualizer through a function before theusingblock ends, cleanup still happens at scope exit — not at the call site.- TypeScript 5.2+ is required. Without it, the
usingkeyword is a syntax error. Checktsconfig.jsontargetandlibbefore using this pattern. [Symbol.dispose]is called synchronously on scope exit. Ifdestroy()cancels async scroll animations, those animations may still be running after theusingblock exits.