⚡ JavaScript: Fix a WeakRef Target Being Collected Too Early
A WeakRef doesn’t keep its target alive — if nothing else in the program holds a strong reference to the object it points to, the garbage collector is free to collect it at any point, including almost immediately, even though you just created the WeakRef and haven’t had a chance to call .deref() yet. The common mistake is wrapping an object that was only ever reachable through a local variable that goes out of scope right after, leaving nothing at all to keep it alive.
🔎 The Problem
function makeRef() {
const data = { big: "payload" };
return new WeakRef(data);
// no strong reference to `data` survives this function call
}
const ref = makeRef();
// `data` may already be eligible for collection here
console.log(ref.deref()); // can legitimately be undefined
✅ Fix: Keep a Real Strong Reference Wherever You Actually Need One
- Keep a strong reference to the target somewhere your program actually controls (a cache map, a module-level variable) for as long as you need it reachable, and only use WeakRef for cases where you explicitly want the object to disappear once nothing else needs it.
- Don’t rely on
.deref()returning the object just because it “was just created” — treat every.deref()call as possibly returning undefined and handle that path regardless of how recently the WeakRef was constructed. - Pair WeakRef with FinalizationRegistry only for cleanup side effects (freeing an external resource), never as a way to guarantee an object survives — those callbacks aren’t guaranteed to run promptly, or at all, before the program exits.
🚨 Why This Is Dangerous
- Code that happens to work in testing because the garbage collector hasn’t run yet can fail unpredictably in production under different memory pressure, making a WeakRef-related bug nearly impossible to reproduce on demand.
A WeakRef describes how you’re willing to lose the object, not a promise about when — if you need it to still be there, something else has to be the reason it survives.
