Sub topic 16
Beyond Weak Collections: WeakRef and FinalizationRegistry
This chapter assumes you know how WeakMap and WeakSet hold keys weakly, and how reachability decides when garbage collection can reclaim an object. It covers two lower-level tools, WeakRef and FinalizationRegistry, and how they differ from weak collections.
The gap weak collections leave
A WeakMap ties a value to the lifetime of an object key. You can never ask it whether a key has been collected, because there is no size and no iteration. That design keeps your code deterministic. It also means a WeakMap cannot help when your keys are strings, such as a cache of large objects looked up by name. A string key would have to sit in a regular Map, and the Map would keep every cached object alive.
WeakRef and FinalizationRegistry fill that gap. They let you observe garbage collection directly, and that power comes with real costs.
WeakRef: a reference that does not keep its target alive
A WeakRef wraps one object. Calling deref() returns the object if it still exists, or undefined if it has been collected.
let target = { label: 'big data' };
const ref = new WeakRef(target);
console.log(ref.deref()?.label); // 'big data'
target = null; // the WeakRef alone no longer keeps the object alive
// At some later, unpredictable point, ref.deref() will return undefined.Always store the result of deref() in a local variable and check it before use. While that variable holds the object, the object is strongly reachable and cannot be collected.
FinalizationRegistry: a callback after collection
A FinalizationRegistry runs a cleanup callback some time after a registered object is collected. You pass a held value to register. The callback receives that held value, never the object itself, which is already gone.
The two tools fit together in a cache keyed by strings:
const cache = new Map();
const registry = new FinalizationRegistry((key) => {
const ref = cache.get(key);
if (ref && ref.deref() === undefined) {
cache.delete(key); // remove the dead entry
}
});
function getImage(name) {
const cached = cache.get(name)?.deref();
if (cached) return cached;
const image = { name, pixels: new Uint8Array(1024) };
cache.set(name, new WeakRef(image));
registry.register(image, name);
return image;
}
const a = getImage('logo');
const b = getImage('logo');
console.log(a === b); // trueThe callback checks deref() again before deleting. A new image may have been cached under the same name after the old one was collected.
Comparing the tools
| Tool | Observes collection? | Typical use |
|---|---|---|
| WeakMap | No | Per-object data and caches keyed by objects |
| WeakSet | No | Marking objects as seen or valid |
| WeakRef | Yes, through `deref()` | Caches whose keys are not the cached objects |
| FinalizationRegistry | Yes, through a callback | Removing stale entries left behind by WeakRefs |
Reach for WeakMap or WeakSet first. Use WeakRef only when the key cannot be the object itself, and treat FinalizationRegistry as a best-effort tidy-up.
Exercise
In the getImage cache, why does the FinalizationRegistry callback receive the key string instead of the image object, and why does it call deref() before deleting the entry?
Show answer
The callback runs after the image has been collected, so the image no longer exists and cannot be passed in. The held value (the key) tells the callback which entry to clean up. It calls deref() because getImage may have stored a new WeakRef under the same key after the old image was collected. Deleting without that check would throw away a live cache entry.
Exercise
You need to attach metadata to DOM elements so that it disappears when the elements are removed and collected. Should you use WeakRef with FinalizationRegistry, or a WeakMap?
Show answer
Use a WeakMap keyed by the elements. The keys are the objects themselves, so the WeakMap ties the metadata's lifetime to each element automatically, with no need to observe collection or write cleanup code.