javascript / expert
Snippet
Memory-Efficient Metadata Storage with WeakMap
At an expert level, managing memory for complex objects or component instances is crucial. WeakMap allows you to associate metadata with objects without preventing those objects from being garbage collected. Unlike a standard Map, WeakMap does not create a strong reference to the key, making it the ideal pattern for internal registries and state tracking in large-scale Next.js applications.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
const instanceRegistry = new WeakMap();function trackComponent(instance, metadata) {instanceRegistry.set(instance, {...metadata,timestamp: performance.now()});}// Usage inside a custom hook or classconst metadata = instanceRegistry.get(this);
nextjs
Breakdown
1
const instanceRegistry = new WeakMap();
Initializes a collection where keys are objects and are held weakly.
2
instanceRegistry.set(instance, { ... });
Attaches metadata to an object instance without modifying the object's own structure.
3
performance.now()
Provides a high-resolution timestamp for precise performance monitoring.