A Deep Dive Into Weak Memory Management in JavaScript | by Jose Granja | Feb, 2022

That WeakRef API is without doubt one of the latest weak APIs. It lets us save a weak reference to an object and pull it once we want it.

use it? It’s a two steps course of.

1. Making a weak reference: the goal param must be an object. Solely these are rubbish collected. You possibly can’t create a WeakRef for a string or quantity for instance.

// making a weak object reference
const ElmentRef = new WeakRef(ingredient);

2. Pulling the reference: to make use of the referenced goal we’ve to make use of the deref(). Step one simply generates an bizarre JavaScript object that incorporates a weak reference to our goal. Not a lot we are able to do with it.

// pulling saved weak object
const ingredient = ElmentRef.deref();

As soon as we use that deref() technique, we’re creating a brand new sturdy reference to the thing. That signifies that object is now not eligible for rubbish assortment till that reference is unused. It wouldn’t make sense that this object might develop into undefined. It could make the function not dependable and ineffective.

Let’s see a full instance:

Be aware within the above code how we at all times have to verify that the return from deref shouldn’t be undefined. The useful resource might have been reclaimed at any time if the DOM ingredient was deleted from the DOM.

Let’s have a look at one other instance. Let’s do a component reminiscence tracker:

Within the above code, we are going to carry on getting console Aspect remains to be on reminiscence statements till the ingredient is worn out from reminiscence at GC.

More Posts