Skip to content
jshacks.dev
Fundamentals

WeakRef and FinalizationRegistry and Why to Use Them Rarely

WeakRef points at an object without keeping it alive, and FinalizationRegistry calls back after collection. See deref, a weak cache and the official warnings.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, npm and Node.js logos.

Garbage collection is invisible to a JavaScript program, by design: nothing in the language tells you when memory is freed, and that guarantee lets engines change their collectors freely. WeakRef and FinalizationRegistry, added in ES2021, are the two places where the program can observe collection, and the specification surrounds them with warnings. Behavior that depends on when an object is collected varies between engines, between versions and between runs of one program, and code that works in a test can fail in production. This post shows the interface, a cache that is the legitimate use, what can and cannot be tested, and the alternatives that avoid weak references altogether. Output is from Node.js 24 as an ES module, and nothing here forces a collection. The weak collections that cover most needs are in the post on WeakMap and WeakSet, and the collector is explained in the post on garbage collection.

WeakRef and deref

A WeakRef wraps an object. Calling deref() returns the object if it is still alive and undefined if it has been collected.

JavaScript
const target = { name: "image-1", bytes: 4096 };
const ref = new WeakRef(target);

console.log(ref.deref() === target);
console.log(ref.deref()?.name);
console.log(typeof ref, Object.prototype.toString.call(ref));

for (const bad of ["text", 42, null]) {
  try {
    new WeakRef(bad);
  } catch (error) {
    console.log(error.name + ": " + error.message);
  }
}

const symbolRef = new WeakRef(Symbol("id"));
console.log(typeof symbolRef.deref());
Text
true
image-1
object [object WeakRef]
TypeError: WeakRef: invalid target
TypeError: WeakRef: invalid target
TypeError: WeakRef: invalid target
symbol

While target is reachable from this module, deref() returns it every time. The reference itself does not count as a reason to keep it, so if the variable goes out of scope and nothing else holds the object, a later deref() may return undefined. A primitive is rejected, and an unregistered symbol is allowed, the same rule as for weak map keys.

The engine also guarantees that a successful deref() keeps the object alive until the current synchronous job ends. That prevents a check-then-use race inside one turn of the event loop, and nothing more.

JavaScript
const ref = new WeakRef({ value: 42 });

function readTwice() {
  const first = ref.deref();
  const second = ref.deref();
  return [first === second, first === undefined];
}

console.log(readTwice());
Text
[ true, false ]

Both reads in one synchronous run agree. A read in a later job can differ, so the standard pattern is to dereference once into a local variable, check it and use the local.

A weak cache

The use case the feature was designed for is a cache that should not prevent collection of its values. Entries hold weak references to expensive objects, and a miss rebuilds the object.

JavaScript
class WeakCache {
  #refs = new Map();
  hits = 0;
  misses = 0;

  get(key, build) {
    const cached = this.#refs.get(key)?.deref();
    if (cached !== undefined) {
      this.hits += 1;
      return cached;
    }

    this.misses += 1;
    const value = build(key);
    this.#refs.set(key, new WeakRef(value));
    return value;
  }

  get size() {
    return this.#refs.size;
  }
}

const cache = new WeakCache();
const build = (key) => ({ key, payload: new Array(1000).fill(key) });

const a = cache.get("a", build);
const again = cache.get("a", build);
const b = cache.get("b", build);

console.log(a === again, a === b);
console.log(cache.hits, cache.misses, cache.size);
Text
true false
1 2 2

The second lookup of "a" was a hit, and "b" was a miss that built a new object. The cache holds the values only weakly, so when callers drop an object the cache lets it go, and the next lookup rebuilds it. Notice what the cache does not do: its Map still holds one WeakRef per key for good, so the keys accumulate even when the values are gone. A real implementation needs to remove dead entries, and that is the job of the registry in the next section.

FinalizationRegistry

A registry runs a callback after an object it tracks has been collected. The callback receives a "held value" you supplied, typically the key to clean up.

JavaScript
const registry = new FinalizationRegistry((heldKey) => {
  console.log("collected:", heldKey);
});

const resource = { id: 1 };
const token = {};

registry.register(resource, "resource-1", token);

console.log(typeof registry.register, typeof registry.unregister);
console.log(registry.unregister(token));
console.log(registry.unregister(token));

try {
  registry.register(resource, resource);
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Text
function function
true
false
TypeError: FinalizationRegistry.prototype.register: target and holdings must not be same

register(target, heldValue, unregisterToken) records the object. The held value must not be the target itself, or the registry would keep it alive and the callback could never run, so passing it is an error. unregister(token) cancels the registration and returns whether one was removed, which is the way to opt out when the cleanup is no longer needed. This example does not wait for a callback, because none is guaranteed. A correct program must work whether or not it ever runs.

Combining the two gives the weak cache a clean-up step: when a value is collected, remove its key.

JavaScript
class CleaningCache {
  #refs = new Map();
  #registry = new FinalizationRegistry((key) => {
    const ref = this.#refs.get(key);
    if (ref && ref.deref() === undefined) this.#refs.delete(key);
  });

  set(key, value) {
    this.#refs.set(key, new WeakRef(value));
    this.#registry.register(value, key);
  }

  get(key) {
    return this.#refs.get(key)?.deref();
  }

  get size() {
    return this.#refs.size;
  }
}

const cache = new CleaningCache();
const kept = { id: 1 };
cache.set("kept", kept);

console.log(cache.get("kept") === kept, cache.size);
Text
true 1

The callback checks that the entry is really dead before deleting it, because a key may have been reused for a new value in the meantime. That check is the kind of detail that makes finalization code hard to get right, and a bug here is a memory leak or a lost entry that shows up only under load.

What the specification warns

The specification text for both features advises against using them. Collection can be delayed arbitrarily, an engine may never run a finalizer, finalizers may run in a different order than collection, and different engines behave differently. Code that needs a resource released at a known time must not use a finalizer for it.

We follow three rules. Never use a finalizer to close a file, release a lock or free anything that must be freed. Never let program logic depend on deref() returning undefined, since a value that stays alive for a few more turns changes the behavior. And treat both features as an optimization that must not change results.

Testing code that uses weak references

Tests for this code are about the strong paths, since the weak ones cannot be forced portably. Assert that a lookup while the value is held returns the same object, that a miss builds a new one, and that a dropped registration does not call back after unregister(). Resist a test that allocates memory until something is collected: it passes on one engine and flakes on another, and it measures the collector more than your code. If a behavior must be verified under collection, run it in a separate, flag-enabled job, such as Node.js with --expose-gc, and keep it out of the default suite.

Alternatives that are deterministic

For a cache keyed by objects, a WeakMap removes entries automatically with no reference and no callback. For releasing resources, try and finally runs at a known point, and the newer using declaration does the same with less code, as covered in the post on explicit resource management. For caches that must be bounded, an explicit eviction policy such as least-recently-used, with a size limit, is predictable and testable, as in the cache shown in the post on Sets and Maps.

JavaScript
const cacheByObject = new WeakMap();

function summarize(report) {
  if (!cacheByObject.has(report)) {
    cacheByObject.set(report, { rows: report.rows.length });
  }
  return cacheByObject.get(report);
}

const report = { rows: [1, 2, 3] };
console.log(summarize(report), summarize(report) === summarize(report));
Text
{ rows: 3 } true

The WeakMap gave a per-object cache with automatic cleanup and no WeakRef at all. Most cases people reach for WeakRef to solve are solved this way.

Where weak references are justified

They appear in framework internals, in large caches of derived data that are expensive to build and cheap to lose and in tools that observe objects they do not own, such as devtools and test utilities. If you are not writing one of those, you probably do not need them. When you do use them, keep the surface small, wrap them in a class that hides the weak behavior, and test the strong path: that a value stays accessible while something references it.

The features are defined in the specification under WeakRef objects and FinalizationRegistry objects, and MDN's pages on WeakRef and FinalizationRegistry repeat the caution.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.