Weak references
WeakMap
Section titled “WeakMap”Keys must be objects; held weakly — if key object is collected, entry disappears.
const meta = new WeakMap();
function attachMeta(domNode, data) { meta.set(domNode, data); // when domNode is GC'd, meta entry goes too}Use when: metadata for DOM/object lifecycle tied to that object.
Don’t use when: you need a string-keyed cache (keys aren’t objects).
WeakRef + FinalizationRegistry (advanced)
Section titled “WeakRef + FinalizationRegistry (advanced)”const registry = new FinalizationRegistry((held) => { console.log('cleaned up', held);});
function track(obj, id) { const ref = new WeakRef(obj); registry.register(obj, id); return ref;}Rare in app code — useful for custom pools and native interop.
flowchart TD strong[Strong reference] --> alive[Object kept alive] weak[WeakMap key] -.-> maybe[Object may be collected]
Weak does not fix strong leaks
Section titled “Weak does not fix strong leaks”If you also store the same object in a global Array, WeakMap won’t help.
Broken
Section titled “Broken”const cache = new Map();const weak = new WeakMap();cache.set(id, hugeObject);weak.set(hugeObject, meta); // hugeObject kept alive by Map key/valueconst weak = new WeakMap();// only weak reference — no strong Map entry