This lesson is picked from next-mdx open source code. In this article, you will learn what a WeakMap in Javascript is.
This lesson is picked from next-mdx open source code. In this article, you will learn what a WeakMap in Javascript is.
WeakMap
A
WeakMap
is a collection of key/value pairs whose keys must be objects or non-registered symbols, with values of any arbitrary JavaScript type, and which does not create strong references to its keys. That is, an object's presence as a key in aWeakMap
does not prevent the object from being garbage collected. Once an object used as a key has been collected, its corresponding values in anyWeakMap
become candidates for garbage collection as well — as long as they aren't strongly referred to elsewhere. — Source
Honestly, I did not understand the above paragraph from MDN docs on the first read. But, after looking at more examples provided in the WeakMap MDN Docs, it all started to make sense.
If you are looking to practice next.js, checkout my website: tthroo.com
Keys in weakmap should be objects.
If you put a string as a key in this map, it simple throws an error.
WeakMap does not have keys and values unlike Map()
The following image shows the prototype of WeakMap
Compare that to a Map shown below
Why WeakMap?
MDN docs has a very detailed explanation about Why WeakMap?
How is this used in next.js source code?
If you look at next.js/packages/next-mdx/mdx-rs-loader.js, WeakMap is used in a variable named cache.
const cache = new WeakMap()
Conclusion:
You want to use a Weakmap to allow garbage collection of values once their keys(object as a key) are garbage collected. This does not apply to Map() as it has “keys” and “values” arrays that maintain references to each key and each value. Next.js uses a WeakMap to enable caching for “@next/mdx” package found in their source code.