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 a WeakMap does not prevent the object from being garbage collected. Once an object used as a key has been collected, its corresponding values in any WeakMap 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: https://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()
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.
Get free courses inspired by the best practices used in open source.
About me:
Website: https://ramunarasinga.com/
Linkedin: https://www.linkedin.com/in/ramu-narasinga-189361128/
Github: https://github.com/Ramu-Narasinga
Email: ramu.narasinga@gmail.com
Top comments (2)
The description on MDN is accurate, but definitely not meant for beginners. A more beginner-friendly way of explaining it would probably start with the problem being solved, which is that:
When using a
Map
to associate some value with an object, as long as the object is in the map and the map itself can be reached, the object won't ever be garbage-collectedThe way
WeakMap
fixes this is simply by not preventing its keys from being collected. They don't let you loop over keys, all you can do is index them and you either get a value or you don't.Caches for things like function memoisation or similar stuff are an application where you will typically find weak data structures like this.
Hey, quite insightful comment. Thank you.