[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"quiz-weakref-finalizationregistry-leak-safe-cache":3,"verticals":25,"search-suggestions":60,"quiz-article-weakref-finalizationregistry-leak-safe-cache":109,"path-membership-weakref-finalizationregistry-leak-safe-cache":300},{"id":4,"slug":5,"kind":6,"title":7,"description":8,"config":9,"verticalId":17,"vertical":18,"course":11,"_count":21,"access":22,"attempts":24,"questionCount":10},"01a1b4aa-fd21-761b-a81e-58dc77665ebc","weakref-finalizationregistry-leak-safe-cache","PRACTICE_QUIZ","WeakRef & FinalizationRegistry — leak-safe caching","Seven questions on why a Map-based cache leaks, what WeakMap already fixes, and where WeakRef and FinalizationRegistry earn their place — and their limits.",{"questionCount":10,"timeLimitSec":11,"shuffleQuestions":12,"shuffleOptions":13,"negativeMarking":14,"passScorePct":15,"maxAttempts":11,"revealAnswers":16,"allowFlagging":12,"allowBacktracking":13},7,null,false,true,0,70,"AFTER_SUBMIT","019fe637-3d33-714b-b57f-23e163ffca0c",{"slug":19,"name":20},"dev","Web Development",{"questions":10},{"allowed":13,"reason":23},"FREE",[],[26,36,48],{"id":17,"slug":19,"name":20,"tagline":27,"description":28,"accentFrom":29,"accentTo":30,"icon":31,"defaultLocale":32,"locales":33,"features":35,"position":14},"Read it. Run it. Prove it.","A post a day on modern web development — most with an editable playground and a quiz that explains every answer. Free, no account needed.","violet-500","cyan-400","◇","en",[32,34],"fa",{"courses":13,"paths":13,"articles":13,"exams":12,"flashcards":12,"packages":13,"community":13,"certificates":13,"teams":13,"commerce":13},{"id":37,"slug":38,"name":39,"tagline":40,"description":41,"accentFrom":42,"accentTo":29,"icon":43,"defaultLocale":32,"locales":44,"features":46,"position":47},"019fe637-3dc2-754c-8657-0f175bfee7c6","lang","Languages","Learn a language the way you learn a codebase.","Grammar explained the way good documentation explains an API — one idea at a time, each with a quiz.","amber-400","⌘",[32,34,45],"es",{"courses":12,"paths":12,"articles":13,"exams":12,"flashcards":13,"packages":12,"community":13,"certificates":13,"teams":12,"commerce":12},2,{"id":49,"slug":50,"name":51,"tagline":52,"description":53,"accentFrom":54,"accentTo":55,"icon":56,"defaultLocale":32,"locales":57,"features":58,"position":59},"7b3c16f2-931d-410e-802e-e1fa4edab7de","soft","Soft Skills","The half of the job nobody wrote documentation for.","Weekly, on the parts of working life that decide more than your code does — first weeks, meetings, interviews, promotions, and the people around you. Written from what actually happens, and recorded as a podcast you can listen to on the walk.","emerald-400","teal-300","◉",[32],{"courses":12,"paths":12,"articles":13,"exams":12,"flashcards":12,"packages":12,"community":13,"certificates":12,"teams":12,"commerce":12},3,[61,65,69,73,77,81,85,89,93,97,101,105],{"slug":62,"name":63,"articles":64},"webdev","Webdev",195,{"slug":66,"name":67,"articles":68},"javascript","Javascript",156,{"slug":70,"name":71,"articles":72},"frontend","Frontend",103,{"slug":74,"name":75,"articles":76},"tutorial","Tutorial",85,{"slug":78,"name":79,"articles":80},"css","Css",56,{"slug":82,"name":83,"articles":84},"typescript","Typescript",36,{"slug":86,"name":87,"articles":88},"performance","Performance",33,{"slug":90,"name":91,"articles":92},"programming","Programming",26,{"slug":94,"name":95,"articles":96},"react","React",23,{"slug":98,"name":99,"articles":100},"node","Node",19,{"slug":102,"name":103,"articles":104},"browser","Browser",18,{"slug":106,"name":107,"articles":108},"nextjs","Nextjs",13,{"id":110,"slug":5,"title":111,"subtitle":11,"excerpt":112,"coverUrl":113,"locale":32,"readingMinutes":114,"publishedAt":115,"viewCount":116,"likeCount":14,"commentCount":14,"author":117,"vertical":122,"topic":123,"tags":125,"_count":130,"playground":132,"body":134,"bodyMd":286,"seo":287,"translationGroupId":290,"series":11,"podcastUrl":11,"verticalId":17,"thread":291,"assessments":293,"translations":296,"quiz":298},"01a1b4aa-fc88-72e4-9a27-437c6ed0bb20","You're Leaking Memory With That Cache. WeakMap Fixes It.","A Map-based cache looks harmless until you check the heap snapshot and find every discarded object still sitting there, held alive by the one `Map` nobody suspected. `WeakMap` fixes the key-as-cache-slot case outright; `WeakRef` and `FinalizationRegistry` cover what's left.","\u002Fmedia\u002Fcovers\u002Fweakref-finalizationregistry-leak-safe-cache.png",6,"2026-11-27T11:40:21.749Z",11,{"id":118,"name":119,"username":120,"avatarUrl":11,"headline":121},"019fe637-3c25-7088-9034-39c9f15dc3c8","Parsa Jiravand","parsa","Frontend engineer · building bestpractic",{"slug":19,"name":20,"accentFrom":29,"accentTo":30},{"slug":66,"name":124},"JavaScript",[126,127,128,129],{"slug":66,"name":67,"color":11},{"slug":62,"name":63,"color":11},{"slug":86,"name":87,"color":11},{"slug":90,"name":91,"color":11},{"assessments":131},1,{"slug":5,"title":133},"WeakRef &amp; FinalizationRegistry — leak-safe cache playground",{"blocks":135,"version":131},[136,140,143,149,152,157,160,163,167,170,173,176,179,182,185,189,192,198,201,204,208,211,214,218,221,224,227,230,234,237,241,244,247,250,253,256,259,262,265,268,271,274,277,280],{"id":137,"html":138,"type":139},"b1","\u003Cp>Open the memory profiler on a page that&#39;s supposed to be idle, and the retained-size graph should flatten out. On this one it didn&#39;t. Every navigation added a little more, and none of it ever came back down.\u003C\u002Fp>","paragraph",{"id":141,"html":142,"type":139},"b2","\u003Cp>The suspect wasn&#39;t a leaked event listener or a forgotten \u003Ccode>setInterval\u003C\u002Fcode> — both had already been ruled out. It was a cache. A perfectly reasonable-looking one:\u003C\u002Fp>",{"id":144,"code":145,"type":146,"language":147,"highlight":148},"b3","const metadataCache = new Map();\n\nfunction getMetadata(record) {\n  if (metadataCache.has(record)) return metadataCache.get(record);\n  const computed = expensiveParse(record);\n  metadataCache.set(record, computed);\n  return computed;\n}","code","js",[],{"id":150,"html":151,"type":139},"b4","\u003Cp>\u003Ccode>record\u003C\u002Fcode> objects came from an API response, got rendered, and were thrown away the moment the user navigated elsewhere. Except they weren&#39;t thrown away — not really. \u003Ccode>metadataCache\u003C\u002Fcode> still had a reference to every single one, and a \u003Ccode>Map\u003C\u002Fcode> never lets go of a key on its own. The garbage collector doesn&#39;t get a vote: as long as \u003Cem>something\u003C\u002Fem> holds a strong reference, the object stays on the heap, parse result and all.\u003C\u002Fp>",{"id":153,"html":154,"text":155,"type":156,"level":47},"b5","Why \u003Ccode>Map\u003C\u002Fcode> can&#39;t be trusted with throwaway keys","Why Map can't be trusted with throwaway keys","heading",{"id":158,"html":159,"type":139},"b6","\u003Cp>This isn&#39;t a bug in \u003Ccode>Map\u003C\u002Fcode> — it&#39;s doing exactly what a \u003Ccode>Map\u003C\u002Fcode> is for. A \u003Ccode>Map\u003C\u002Fcode> is built to \u003Cstrong>keep\u003C\u002Fstrong> what you put in it until you explicitly delete it. That&#39;s the correct behavior for a cache keyed by a string or a small fixed set of values. It&#39;s the wrong behavior for a cache keyed by objects whose whole lifecycle is &quot;used once, then gone&quot; — because nothing ever calls \u003Ccode>.delete()\u003C\u002Fcode> for you, and the moment you forget to, the cache becomes a second copy of every object your app ever touched, held open forever.\u003C\u002Fp>",{"id":161,"html":162,"type":139},"b7","\u003Cp>The usual first fix is \u003Ccode>WeakMap\u003C\u002Fcode>:\u003C\u002Fp>",{"id":164,"code":165,"type":146,"language":147,"highlight":166},"b8","const metadataCache = new WeakMap(); \u002F\u002F same calls, weak keys\n\nfunction getMetadata(record) {\n  if (metadataCache.has(record)) return metadataCache.get(record);\n  const computed = expensiveParse(record);\n  metadataCache.set(record, computed);\n  return computed;\n}",[],{"id":168,"html":169,"type":139},"b9","\u003Cp>Same API, one word different, and the leak is gone. A \u003Ccode>WeakMap\u003C\u002Fcode> holds its keys \u003Cem>weakly\u003C\u002Fem>: once nothing else in the program references a given \u003Ccode>record\u003C\u002Fcode>, the engine is free to collect it, and its entry in the \u003Ccode>WeakMap\u003C\u002Fcode> disappears with it — automatically, with no \u003Ccode>.delete()\u003C\u002Fcode> anywhere. \u003Ccode>WeakMap\u003C\u002Fcode> has existed since ES2015, and for &quot;cache keyed by an object, evict when the object is gone,&quot; it&#39;s the entire answer. Reach for it first.\u003C\u002Fp>",{"id":171,"html":172,"type":139},"b10","\u003C!-- playground:start -->",{"id":174,"html":175,"text":175,"type":156,"level":47},"b11","🎮 Try it yourself",{"id":177,"html":178,"type":139},"b12","\u003Cp>\u003Cstrong>\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fweakref-finalizationregistry-leak-safe-cache\u002Fplayground\">▶️ Open the interactive playground →\u003C\u002Fa>\u003C\u002Fstrong>\u003C\u002Fp>",{"id":180,"html":181,"type":139},"b13","\u003Cp>\u003Cem>Runs right in your browser — poke at it and watch the concept react live.\u003C\u002Fem>\u003C\u002Fp>",{"id":183,"html":184,"type":139},"b14","\u003C!-- playground:end -->",{"id":186,"html":187,"text":188,"type":156,"level":47},"b15","The case \u003Ccode>WeakMap\u003C\u002Fcode> can&#39;t cover","The case WeakMap can't cover",{"id":190,"html":191,"type":139},"b16","\u003Cp>\u003Ccode>WeakMap\u003C\u002Fcode> only solves the problem when the weak thing is a \u003Cem>map key\u003C\u002Fem>. Two situations fall outside that:\u003C\u002Fp>",{"id":193,"type":194,"items":195,"ordered":12},"b17","list",[196,197],"You need to hold a weak reference \u003Cstrong>by itself\u003C\u002Fstrong> — in a class field, an array entry, a plain object property — not as a \u003Ccode>Map\u003C\u002Fcode> key at all. \u003Ccode>WeakMap\u003C\u002Fcode>\u002F\u003Ccode>WeakSet\u003C\u002Fcode> have no API for that; they only accept objects as keys or set members.","You need to \u003Cstrong>do something\u003C\u002Fstrong> when the object actually gets collected — close a \u003Ccode>WebSocket\u003C\u002Fcode>, cancel a subscription, remove an entry from an unrelated index — and \u003Ccode>WeakMap\u003C\u002Fcode> gives you silence. The entry just vanishes; nothing tells your code it happened.",{"id":199,"html":200,"type":139},"b18","\u003Cp>That&#39;s what the other two ES2021 additions are for.\u003C\u002Fp>",{"id":202,"html":203,"type":139},"b19","\u003Cp>\u003Cstrong>\u003Ccode>WeakRef\u003C\u002Fcode>\u003C\u002Fstrong> wraps a single object in a container you can hold anywhere, without that container keeping the object alive:\u003C\u002Fp>",{"id":205,"code":206,"type":146,"language":147,"highlight":207},"b20","let ref = new WeakRef(record);\n\nref.deref(); \u002F\u002F the record, while it's still alive\nref.deref(); \u002F\u002F undefined, once nothing else references it — could be later in the same function",[],{"id":209,"html":210,"type":139},"b21","\u003Cp>\u003Ccode>.deref()\u003C\u002Fcode> is the only thing you do with it: call it, and either get the live object back or \u003Ccode>undefined\u003C\u002Fcode>. There is no event, no promise, no way to ask &quot;is it gone yet&quot; without calling \u003Ccode>.deref()\u003C\u002Fcode> and checking.\u003C\u002Fp>",{"id":212,"html":213,"type":139},"b22","\u003Cp>\u003Cstrong>\u003Ccode>FinalizationRegistry\u003C\u002Fcode>\u003C\u002Fstrong> is the piece that gives you a callback instead of a poll:\u003C\u002Fp>",{"id":215,"code":216,"type":146,"language":147,"highlight":217},"b23","const registry = new FinalizationRegistry((heldValue) => {\n  console.log(`cleaning up after ${heldValue}`);\n  releaseExternalResource(heldValue);\n});\n\nregistry.register(record, record.id);",[],{"id":219,"html":220,"type":139},"b24","\u003Cp>\u003Ccode>register(target, heldValue, unregisterToken?)\u003C\u002Fcode> watches \u003Ccode>target\u003C\u002Fcode>. Once \u003Ccode>target\u003C\u002Fcode> becomes unreachable and the engine gets around to collecting it, the registry calls your callback with \u003Ccode>heldValue\u003C\u002Fcode> — never with \u003Ccode>target\u003C\u002Fcode> itself, because the callback runs \u003Cem>after\u003C\u002Fem> \u003Ccode>target\u003C\u002Fcode> is already gone. That&#39;s also why \u003Ccode>target\u003C\u002Fcode> and \u003Ccode>heldValue\u003C\u002Fcode> can&#39;t be the same object: pass the same reference for both and \u003Ccode>register()\u003C\u002Fcode> throws a \u003Ccode>TypeError\u003C\u002Fcode>, because the registry holding \u003Ccode>heldValue\u003C\u002Fcode> strongly would defeat the entire point by keeping \u003Ccode>target\u003C\u002Fcode> alive forever.\u003C\u002Fp>",{"id":222,"html":223,"type":139},"b25","\u003Cp>If you dispose of something yourself before GC gets to it, call \u003Ccode>registry.unregister(unregisterToken)\u003C\u002Fcode> — a third argument to \u003Ccode>register()\u003C\u002Fcode> — so the callback doesn&#39;t fire twice.\u003C\u002Fp>",{"id":225,"html":226,"text":226,"type":156,"level":47},"b26","Building a cache that cleans up after itself",{"id":228,"html":229,"type":139},"b27","\u003Cp>Put the two together and the parse-result cache gets an upgrade \u003Ccode>WeakMap\u003C\u002Fcode> alone couldn&#39;t give it: logging (or releasing an external resource) the moment an entry is actually swept.\u003C\u002Fp>",{"id":231,"code":232,"type":146,"language":147,"highlight":233},"b28","const metadataCache = new WeakMap();\nconst cleanupLog = new FinalizationRegistry((id) => {\n  console.log(`metadata for record ${id} was collected`);\n});\n\nfunction getMetadata(record) {\n  if (metadataCache.has(record)) return metadataCache.get(record);\n  const computed = expensiveParse(record);\n  metadataCache.set(record, computed);\n  cleanupLog.register(record, record.id);\n  return computed;\n}",[],{"id":235,"html":236,"type":139},"b29","\u003Cp>The \u003Ccode>WeakMap\u003C\u002Fcode> still does the actual weak-caching — it&#39;s the right tool for that half. The \u003Ccode>FinalizationRegistry\u003C\u002Fcode> is bolted on purely for visibility and side effects: if \u003Ccode>getMetadata\u003C\u002Fcode> also opened a \u003Ccode>BroadcastChannel\u003C\u002Fcode> per record, this is where you&#39;d close it, instead of hoping the caller remembers to.\u003C\u002Fp>",{"id":238,"html":239,"text":240,"type":156,"level":47},"b30","The guarantee you don&#39;t get — and why that&#39;s fine","The guarantee you don't get — and why that's fine",{"id":242,"html":243,"type":139},"b31","\u003Cp>Here&#39;s the part that trips people up the first time they read the spec: \u003Cstrong>there is no guarantee a \u003Ccode>FinalizationRegistry\u003C\u002Fcode> callback ever runs.\u003C\u002Fstrong> Not &quot;runs eventually&quot; — possibly never. If the page unloads first, if the engine decides the cleanup isn&#39;t worth the cycles, if the object happens to never get collected during the page&#39;s lifetime — the callback is simply skipped. ECMA-262 says this on purpose, because it leaves engines free to optimize garbage collection however they want without being locked into a cleanup contract.\u003C\u002Fp>",{"id":245,"html":246,"type":139},"b32","\u003Cp>That single sentence should decide every use of these two APIs. \u003Ccode>WeakRef\u003C\u002Fcode> and \u003Ccode>FinalizationRegistry\u003C\u002Fcode> are for \u003Cstrong>optimization and housekeeping\u003C\u002Fstrong> — a cache that&#39;s allowed to forget things, a debug log, releasing a resource a little sooner than it otherwise would be. They are the wrong tool for anything that must happen: closing a file handle your app&#39;s correctness depends on, flushing data the user will notice if it&#39;s lost, releasing a lock another process is waiting on. For deterministic cleanup, reach for an explicit \u003Ccode>dispose()\u003C\u002Fcode>\u002F\u003Ccode>close()\u003C\u002Fcode> call (or \u003Ccode>using\u003C\u002Fcode>, if your runtime supports resource management) — something that runs because your code said so, not because the garbage collector eventually agreed to.\u003C\u002Fp>",{"id":248,"html":249,"text":249,"type":156,"level":47},"b33","What actually changed",{"id":251,"html":252,"type":139},"b34","\u003Cp>\u003Ccode>WeakMap\u003C\u002Fcode> and \u003Ccode>WeakSet\u003C\u002Fcode> have quietly prevented this class of leak since 2015; most caches never needed anything newer. \u003Ccode>WeakRef\u003C\u002Fcode> and \u003Ccode>FinalizationRegistry\u003C\u002Fcode> — both ES2021, both supported in every evergreen browser and in Node since 14.6 — only earn their place when the weak reference isn&#39;t a map key, or when something genuinely needs to happen on collection rather than just disappear quietly.\u003C\u002Fp>",{"id":254,"html":255,"type":139},"b35","\u003Cp>The fix for the original leak, in the end, was one word: \u003Ccode>Map\u003C\u002Fcode> became \u003Ccode>WeakMap\u003C\u002Fcode>. The heap snapshot flattened out on the next deploy. But the question worth sitting with is the one that found it in the first place — next time a retained-size graph only ever goes up, which cache in your code is the one still holding the door open?\u003C\u002Fp>",{"id":257,"html":258,"type":139},"b36","\u003C!-- quiz:start -->",{"id":260,"html":261,"text":261,"type":156,"level":47},"b37","🧠 Test yourself",{"id":263,"html":264,"type":139},"b38","\u003Cp>Think it clicked? \u003Cstrong>\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fweakref-finalizationregistry-leak-safe-cache\u002Fquiz\">Take the 7-question quiz →\u003C\u002Fa>\u003C\u002Fstrong>\u003C\u002Fp>",{"id":266,"html":267,"type":139},"b39","\u003Cp>\u003Cem>Instant feedback, a hint on every question, and an explanation for each answer — right or wrong.\u003C\u002Fem>\u003C\u002Fp>",{"id":269,"html":270,"type":139},"b40","\u003C!-- quiz:end -->",{"id":272,"type":273},"b41","divider",{"id":275,"html":276,"type":139},"b42","\u003Cp>🚀 \u003Cstrong>Want more like this?\u003C\u002Fstrong> Every guide, playground, and quiz lives on \u003Cstrong>\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002F\">bestpractic.org\u003C\u002Fa>\u003C\u002Fstrong> — open it and \u003Cstrong>\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002F\">sign up free\u003C\u002Fa>\u003C\u002Fstrong> so the next one finds you.\u003C\u002Fp>",{"id":278,"html":279,"type":139},"b43","\u003Cp>\u003Cem>Thanks for reading! Let&#39;s stay connected:\u003C\u002Fem>\u003C\u002Fp>",{"id":281,"type":194,"items":282,"ordered":12},"b44",[283,284,285],"⭐ \u003Cstrong>GitHub\u003C\u002Fstrong> — follow me and star the projects: \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fparsajiravand\">github.com\u002Fparsajiravand\u003C\u002Fa>","💬 \u003Cstrong>Discord\u003C\u002Fstrong> — join the frontend best-practices community: \u003Ca href=\"https:\u002F\u002Fdiscord.gg\u002Fd9KRhuAwQ\">discord.gg\u002Fd9KRhuAwQ\u003C\u002Fa>","📸 \u003Cstrong>Instagram\u003C\u002Fstrong> — frontend best practices, daily: \u003Ca href=\"https:\u002F\u002Fwww.instagram.com\u002Fbestpractice___\u002F\">@bestpractice___\u003C\u002Fa>","Open the memory profiler on a page that's supposed to be idle, and the retained-size graph should flatten out. On this one it didn't. Every navigation added a little more, and none of it ever came back down.\n\nThe suspect wasn't a leaked event listener or a forgotten `setInterval` — both had already been ruled out. It was a cache. A perfectly reasonable-looking one:\n\n```js\nconst metadataCache = new Map();\n\nfunction getMetadata(record) {\n  if (metadataCache.has(record)) return metadataCache.get(record);\n  const computed = expensiveParse(record);\n  metadataCache.set(record, computed);\n  return computed;\n}\n```\n\n`record` objects came from an API response, got rendered, and were thrown away the moment the user navigated elsewhere. Except they weren't thrown away — not really. `metadataCache` still had a reference to every single one, and a `Map` never lets go of a key on its own. The garbage collector doesn't get a vote: as long as *something* holds a strong reference, the object stays on the heap, parse result and all.\n\n## Why `Map` can't be trusted with throwaway keys\n\nThis isn't a bug in `Map` — it's doing exactly what a `Map` is for. A `Map` is built to **keep** what you put in it until you explicitly delete it. That's the correct behavior for a cache keyed by a string or a small fixed set of values. It's the wrong behavior for a cache keyed by objects whose whole lifecycle is \"used once, then gone\" — because nothing ever calls `.delete()` for you, and the moment you forget to, the cache becomes a second copy of every object your app ever touched, held open forever.\n\nThe usual first fix is `WeakMap`:\n\n```js\nconst metadataCache = new WeakMap(); \u002F\u002F same calls, weak keys\n\nfunction getMetadata(record) {\n  if (metadataCache.has(record)) return metadataCache.get(record);\n  const computed = expensiveParse(record);\n  metadataCache.set(record, computed);\n  return computed;\n}\n```\n\nSame API, one word different, and the leak is gone. A `WeakMap` holds its keys *weakly*: once nothing else in the program references a given `record`, the engine is free to collect it, and its entry in the `WeakMap` disappears with it — automatically, with no `.delete()` anywhere. `WeakMap` has existed since ES2015, and for \"cache keyed by an object, evict when the object is gone,\" it's the entire answer. Reach for it first.\n\n\u003C!-- playground:start -->\n\n## 🎮 Try it yourself\n\n**[▶️ Open the interactive playground →](https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fweakref-finalizationregistry-leak-safe-cache\u002Fplayground)**\n\n_Runs right in your browser — poke at it and watch the concept react live._\n\n\u003C!-- playground:end -->\n\n## The case `WeakMap` can't cover\n\n`WeakMap` only solves the problem when the weak thing is a *map key*. Two situations fall outside that:\n\n- You need to hold a weak reference **by itself** — in a class field, an array entry, a plain object property — not as a `Map` key at all. `WeakMap`\u002F`WeakSet` have no API for that; they only accept objects as keys or set members.\n- You need to **do something** when the object actually gets collected — close a `WebSocket`, cancel a subscription, remove an entry from an unrelated index — and `WeakMap` gives you silence. The entry just vanishes; nothing tells your code it happened.\n\nThat's what the other two ES2021 additions are for.\n\n**`WeakRef`** wraps a single object in a container you can hold anywhere, without that container keeping the object alive:\n\n```js\nlet ref = new WeakRef(record);\n\nref.deref(); \u002F\u002F the record, while it's still alive\nref.deref(); \u002F\u002F undefined, once nothing else references it — could be later in the same function\n```\n\n`.deref()` is the only thing you do with it: call it, and either get the live object back or `undefined`. There is no event, no promise, no way to ask \"is it gone yet\" without calling `.deref()` and checking.\n\n**`FinalizationRegistry`** is the piece that gives you a callback instead of a poll:\n\n```js\nconst registry = new FinalizationRegistry((heldValue) => {\n  console.log(`cleaning up after ${heldValue}`);\n  releaseExternalResource(heldValue);\n});\n\nregistry.register(record, record.id);\n```\n\n`register(target, heldValue, unregisterToken?)` watches `target`. Once `target` becomes unreachable and the engine gets around to collecting it, the registry calls your callback with `heldValue` — never with `target` itself, because the callback runs *after* `target` is already gone. That's also why `target` and `heldValue` can't be the same object: pass the same reference for both and `register()` throws a `TypeError`, because the registry holding `heldValue` strongly would defeat the entire point by keeping `target` alive forever.\n\nIf you dispose of something yourself before GC gets to it, call `registry.unregister(unregisterToken)` — a third argument to `register()` — so the callback doesn't fire twice.\n\n## Building a cache that cleans up after itself\n\nPut the two together and the parse-result cache gets an upgrade `WeakMap` alone couldn't give it: logging (or releasing an external resource) the moment an entry is actually swept.\n\n```js\nconst metadataCache = new WeakMap();\nconst cleanupLog = new FinalizationRegistry((id) => {\n  console.log(`metadata for record ${id} was collected`);\n});\n\nfunction getMetadata(record) {\n  if (metadataCache.has(record)) return metadataCache.get(record);\n  const computed = expensiveParse(record);\n  metadataCache.set(record, computed);\n  cleanupLog.register(record, record.id);\n  return computed;\n}\n```\n\nThe `WeakMap` still does the actual weak-caching — it's the right tool for that half. The `FinalizationRegistry` is bolted on purely for visibility and side effects: if `getMetadata` also opened a `BroadcastChannel` per record, this is where you'd close it, instead of hoping the caller remembers to.\n\n## The guarantee you don't get — and why that's fine\n\nHere's the part that trips people up the first time they read the spec: **there is no guarantee a `FinalizationRegistry` callback ever runs.** Not \"runs eventually\" — possibly never. If the page unloads first, if the engine decides the cleanup isn't worth the cycles, if the object happens to never get collected during the page's lifetime — the callback is simply skipped. ECMA-262 says this on purpose, because it leaves engines free to optimize garbage collection however they want without being locked into a cleanup contract.\n\nThat single sentence should decide every use of these two APIs. `WeakRef` and `FinalizationRegistry` are for **optimization and housekeeping** — a cache that's allowed to forget things, a debug log, releasing a resource a little sooner than it otherwise would be. They are the wrong tool for anything that must happen: closing a file handle your app's correctness depends on, flushing data the user will notice if it's lost, releasing a lock another process is waiting on. For deterministic cleanup, reach for an explicit `dispose()`\u002F`close()` call (or `using`, if your runtime supports resource management) — something that runs because your code said so, not because the garbage collector eventually agreed to.\n\n## What actually changed\n\n`WeakMap` and `WeakSet` have quietly prevented this class of leak since 2015; most caches never needed anything newer. `WeakRef` and `FinalizationRegistry` — both ES2021, both supported in every evergreen browser and in Node since 14.6 — only earn their place when the weak reference isn't a map key, or when something genuinely needs to happen on collection rather than just disappear quietly.\n\nThe fix for the original leak, in the end, was one word: `Map` became `WeakMap`. The heap snapshot flattened out on the next deploy. But the question worth sitting with is the one that found it in the first place — next time a retained-size graph only ever goes up, which cache in your code is the one still holding the door open?\n\n\u003C!-- quiz:start -->\n\n## 🧠 Test yourself\n\nThink it clicked? **[Take the 7-question quiz →](https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fweakref-finalizationregistry-leak-safe-cache\u002Fquiz)**\n\n_Instant feedback, a hint on every question, and an explanation for each answer — right or wrong._\n\n\u003C!-- quiz:end -->\n\n---\n\n🚀 **Want more like this?** Every guide, playground, and quiz lives on **[bestpractic.org](https:\u002F\u002Fbestpractic.org\u002F)** — open it and **[sign up free](https:\u002F\u002Fbestpractic.org\u002F)** so the next one finds you.\n\n*Thanks for reading! Let's stay connected:*\n\n- ⭐ **GitHub** — follow me and star the projects: [github.com\u002Fparsajiravand](https:\u002F\u002Fgithub.com\u002Fparsajiravand)\n- 💬 **Discord** — join the frontend best-practices community: [discord.gg\u002Fd9KRhuAwQ](https:\u002F\u002Fdiscord.gg\u002Fd9KRhuAwQ)\n- 📸 **Instagram** — frontend best practices, daily: [@bestpractice___](https:\u002F\u002Fwww.instagram.com\u002Fbestpractice___\u002F)",{"title":111,"canonical":288,"description":289},"https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fweakref-finalizationregistry-leak-safe-cache","A Map-based cache looks harmless until you check the heap snapshot and find every discarded object still sitting there, held alive by the one `Map` nobody suspected. `WeakMap` fixe","01a1b4aa-fc88-72e4-9a27-47dc7f6ce5f5",{"id":292,"locked":12},"01a1b4aa-fcf7-7632-aca4-6846bcbb98d3",[294],{"id":4,"slug":5,"title":7,"_count":295},{"questions":10},[297],{"locale":32,"slug":5},{"id":4,"slug":5,"title":7,"_count":299,"questionCount":10},{"questions":10},[]]