Explicit Resource Management (using)
Problem
You create a virtualizer inside a function or block scope and want it disposed automatically when the block exits — without a try/finally or a manual dispose() call.
Solution
ts
import { createVirtualizer } from '@vielzeug/scroll';
function renderList(scrollEl: HTMLElement, rows: string[]) {
using virt = createVirtualizer(scrollEl, {
count: rows.length,
estimateSize: 36,
onChange: ({ items, totalSize }) => {
// render...
},
});
// ... synchronous setup ...
} // virt.dispose() 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. Ifdispose()cancels async scroll animations, those animations may still be running after theusingblock exits.