JavaScript

WeakRef Object Cache

by @admin
10h ago
Apr 28, 2026
Public
A cache backed by WeakRef and FinalizationRegistry. Stored values are held weakly — the garbage collector can reclaim them if memory pressure is high, and the registry automatically cleans up stale entries from the internal map. Ideal for caching large objects (DOM nodes, rendered images) without causing memory leaks.
JavaScript
function createWeakCache() {
  const cache   = new Map();
  const registry = new FinalizationRegistry((key) => cache.delete(key));

  return {
    set(key, value) {
      cache.set(key, new WeakRef(value));
      registry.register(value, key);
    },
    get(key) {
      return cache.get(key)?.deref() ?? null;
    },
    has(key) {
      return this.get(key) !== null;
    },
  };
}

// Usage
const imgCache = createWeakCache();
const img = new Image();
img.src = '/hero.jpg';
imgCache.set('hero', img);
console.log(imgCache.get('hero')); // Image element (while alive)
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.