top of page
Logo der Online Agentur mdwp

WeakMap

While not being specific to React JS, the term WeakMap refers to a JavaScript built-in object that holds key-value pairs where the keys are weakly referenced which means that they are subject to garbage collection if they are not referenced elsewhere in the application. This is a stark contrast with regular Map objects, where keys can be of any type and are not subject to garbage collection.

WeakMaps have a few specific use cases in JavaScript, including data privacy, as it enables you to uniquely associate information with a DOM node without exposing this information. They can also be used to avoid memory leaks, as they allow the associated values to be garbage collected when the key object is no longer used.

Here is a simple example of creating and using a WeakMap:

```jsx
let exampleWeakMap = new WeakMap();

let obj = { key: 'example' };
exampleWeakMap.set(obj, 'This is an example value');

// As long as obj is not removed, we can access the value like so
console.log(exampleWeakMap.get(obj)); // output: This is an example value

// If we overwrite the obj, the weakMap will no longer have reference to the value
obj = null;
console.log(exampleWeakMap.get(obj)); // output: undefined
```

In the last example, because we've set `obj` to `null`, the garbage collector will remove the orphaned value in the `exampleWeakMap` during its next cycle. Bear in mind that you cannot iterate over the keys or values of a WeakMap which gives you less control but enhances data protection.

bottom of page