WeakRef and FinalizationRegistry: caches that do not leak memory
A cache in a long-living admin page (a block editor plugin, a dashboard that runs all day) easily becomes a memory leak: every object put into a Map stays alive as long as the map does, even when nothing else uses it. WeakMap solves this for caches keyed by objects. For caches keyed by strings or numbers, WeakRef holds a value without keeping it alive, and FinalizationRegistry tells the cache when a value was collected so it can remove the stale key.
Problem: A media management screen caches decoded image previews in a Map keyed by attachment ID. After an hour of browsing, the tab uses 1.5 GB, because previews of images that are long off-screen are still referenced by the cache.
Solution: Use WeakMap where the key is an object (a DOM node, a model), and for ID-keyed caches store new WeakRef( value ) in the map, read it with deref(), and remove entries in a FinalizationRegistry callback. Keep a small strong LRU list for the most recent items so the cache still hits.
First choice: WeakMap
const previewByElement = new WeakMap();
function haPreviewFor( element ) {
let preview = previewByElement.get( element );
if ( ! preview ) {
preview = haBuildPreview( element.dataset.attachmentId );
previewByElement.set( element, preview );
}
return preview;
}
A WeakMap does not keep its keys alive: when the element is removed from the page and nothing else references it, the entry disappears with it. No cleanup code, no APIs with uncertain timing. Whenever the data belongs to an object, this is the right tool.
ID keys: WeakRef plus FinalizationRegistry
class HaWeakCache {
#map = new Map(); // id -> WeakRef
#registry = new FinalizationRegistry( ( id ) => {
const ref = this.#map.get( id );
if ( ref && ! ref.deref() ) {
this.#map.delete( id ); // the value was collected: drop the stale entry
}
} );
get( id ) {
return this.#map.get( id )?.deref();
}
set( id, value ) {
this.#map.set( id, new WeakRef( value ) );
this.#registry.register( value, id );
}
}
const previews = new HaWeakCache();
async function haGetPreview( id ) {
let preview = previews.get( id );
if ( ! preview ) {
const meta = await ( await fetch( `/wp-json/wp/v2/media/${ id }?_fields=media_details` ) ).json();
preview = await haDecode( meta.media_details );
previews.set( id, preview );
}
return preview;
}
deref() returns the value, or undefined once the garbage collector has reclaimed it. The value must be an object; strings and numbers cannot be held weakly. The check in the callback (! ref.deref()) matters: the ID may have been set again with a new value before the callback ran.
Keep the recent items strongly
A purely weak cache can lose everything at the next garbage collection, which may be very soon. A small strong list keeps the last items alive:
const recent = [];
function haKeep( value, max = 50 ) {
recent.push( value );
if ( recent.length > max ) recent.shift();
}
Call haKeep( preview ) after previews.set(): the last 50 previews are guaranteed hits, older ones live as long as the browser does not need the memory.
What not to rely on
- The garbage collector decides when (and whether) values are collected. Finalization callbacks may run late or never, for example when the tab is closed. Never use them for required work like saving data or releasing server resources.
- Do not use
WeakRefto “check whether an object is still used”; the answer depends on engine internals and changes between browsers. - Detached DOM nodes are the most common leak in admin scripts anyway: remove event listeners and references when a component is unmounted, an
AbortControllersignal onaddEventListenermakes that one call.
NOTE: WeakRef and FinalizationRegistry exist in all browsers since 2021 (Safari 14.1 was the last) and in Node.js 14.6+. To find out whether a cache leaks at all, take two heap snapshots in Chrome DevTools (Memory panel) before and after some use and compare the retained size of the cache. Deep copies, another memory topic in admin code: structuredClone().