Developers are always searching for the new exciting stuff and so they are excited when they find something new. Finally a new hammer to put any kind of nail into all walls you can possibly find! But with time, you accept the harsh truth that new and exciting technology should be avoided to be used instantly when you discover them.
Still, you should learn about them and there is actually a great introduction to the topic on YouTube that i would definitely recommend you to watch:
What is the difference between a normal
Map and a
WeakMap? There are two key (pun intended) factors that differentiate them. For the start, only an object is allowed as a key for a
WeakMap and you can't iterate over a
Imagine the object you define as a key as something like real key, that you can't copy. A
Nonetheless some developers still use a WeakMap for example to add metadata to objects, that they also want to be garbage collected when the object is garbage collected. Or just want to add that metadata in some part of the code and need the metadata only there. But ask yourself: Is it worth the risk to use something that can possibly behave different than you expect? And will your coworkers understand it, when they have to review or even change your code later? There is a good chance that they have never worked with WeakMaps and will therefore possibly introduce some bugs to your system that are hard to fix.
Right now you probably ask yourself why stuff like WeakMaps do exist in the first place? To understand this better, let's talk about
A WeakRef holds a weak reference to an object. So like the WeakMap, the object can be garbage collected even if there still exists a WeakRef that contains an object.
Why do we need WeakRefs actually? One of the most popular reasons has something to do with the
FinalizationRegistry and WebAssembly. Because
Otherwise it would be really hard to recognize if an object was garbage collected and you probably have to use much more memory than you would need. And this is especially interesting for WebAssembly. Because most of the WebAssembly projects are created with performance and speed at the heart of the project. So this part becomes really important.
As you have probably already realized it is not only hard to use
WeakRef, but it can also lead to some bugs that are even harder to debug. And with modern state management libraries there are better ways to add meta data to objects. So, as the official specs will tell you: Try to avoid using them.