WeakSet() in react-scan source code.
In this article, we review a code snippet from react-scan source code.
export const ignoredProps = new WeakSet<
Exclude<ReactNode, undefined | null | string | number | boolean | bigint>
>();
export const ignoreScan = (node: ReactNode) => {
if (node && typeof node === 'object') {
ignoredProps.add(node);
}
};
I found this code snippet in a file, core/index.ts. Why not use a proper Set? why would react-scan author decide to use WeakSet? To draw some conclusion around that, we first need to understand difference between WeakSet and Set in JavaScript.
WeakSet
A WeakSet
is a collection of garbage-collectable values, including objects and non-registered symbols. A value in the WeakSet
may only occur once. It is unique in the WeakSet
's collection.
Read more about WeakSet.
Set
The Set
object lets you store unique values of any type, whether primitive values or object references.
Read more about Set
WeakSet vs Set
Values of WeakSets must be garbage-collectable. Most primitive data types can be arbitrarily created and don’t have a lifetime, so they cannot be stored. Objects and non-registered symbols can be stored because they are garbage-collectable.
The main differences to the Set
object are:
-
WeakSet
s are collections of objects and symbols only. They cannot contain arbitrary values of any type, asSet
s can. -
The
WeakSet
is weak, meaning references to objects in aWeakSet
are held weakly. If no other references to a value stored in theWeakSet
exist, those values can be garbage collected.
Coming back to the code snippet in react-scan
export const ignoreScan = (node: ReactNode) => {
if (node && typeof node === 'object') {
ignoredProps.add(node);
}
};
Now it makes sense why typeof node === ‘object’ check is in place. Can you guess why? this is because only Object and Symbols can be stored in the WeakMap that are garbage collectable if they are not referenced elsewhere.
About me:
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.
I am open to work on interesting projects. Send me an email at ramu.narasinga@gmail.com
My Github — https://github.com/ramu-narasinga
My website — https://ramunarasinga.com
My Youtube channel — https://www.youtube.com/@thinkthroo
Learning platform — https://thinkthroo.com
Codebase Architecture — https://app.thinkthroo.com/architecture
Best practices — https://app.thinkthroo.com/best-practices
Production-grade projects — https://app.thinkthroo.com/production-grade-projects