javascript / intermediate
Snippet
Managing Leak-Free Object Metadata Using WeakMap in Vue Lifecycle Hooks
Attaching custom metadata to DOM elements or external objects via standard Maps can lead to memory leaks when components unmount and elements are removed. A WeakMap holds weak references to its object keys, allowing garbage collection to reclaim memory automatically without manual cleanup in unmount hooks.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { onMounted } from 'vue';const elementMetaRegistry = new WeakMap();export function useElementMetadataTracker(elementRef) {onMounted(() => {if (elementRef.value) {elementMetaRegistry.set(elementRef.value, {registeredAt: Date.now(),interactionCount: 0});}});const incrementInteraction = () => {const el = elementRef.value;if (el && elementMetaRegistry.has(el)) {const meta = elementMetaRegistry.get(el);meta.interactionCount += 1;}};return { incrementInteraction };}
vue
Breakdown
1
const elementMetaRegistry = new WeakMap();
Creates a WeakMap where object keys are held weakly to avoid retaining memory when elements are deleted.
2
elementMetaRegistry.set(elementRef.value, {
Associates metadata records directly to the mounted DOM node instance.
3
const meta = elementMetaRegistry.get(el);
Retrieves the associated metadata for the given element without mutating the underlying DOM node directly.