WeakRef and FinalizationRegistry provide advanced memory management capabilities. Here's how to use them responsibly.
Basic WeakRef#
WeakRef for Caching#
FinalizationRegistry#
Resource Cleanup Pattern#
Unregister Token#
WeakRef + FinalizationRegistry#
DOM Element Tracking#
Event Listener Management#
Image Cache Example#
Object Pool with Cleanup#
Important Caveats#
Best Practices#
Valid Use Cases:
✓ Caches that can lose entries
✓ Tracking external resources
✓ Secondary cleanup mechanism
✓ Debugging memory leaks
Requirements:
✓ Must work if cleanup never happens
✓ Must work if cleanup is delayed
✓ Primary cleanup should be explicit
✓ Finalization is a fallback
Performance:
✓ WeakRef.deref() is fast
✓ Don't create many WeakRefs
✓ Clean up dead refs periodically
✓ Avoid in hot paths
Avoid:
✗ Critical resource cleanup
✗ Side effects with timing requirements
✗ Assuming GC timing
✗ Complex finalization logic
Conclusion#
WeakRef and FinalizationRegistry enable advanced memory management patterns like weak caches and automatic resource cleanup. WeakRef holds references without preventing garbage collection, while FinalizationRegistry runs callbacks after objects are collected. Always design systems to work correctly without relying on finalization timing, and use these APIs as optimization or fallback mechanisms, not for critical cleanup logic.