javascript / expert
Snippet
Preventing Memory Leakage in Reactive Graph Trees using WeakSet References
Traversing reactive objects can lead to infinite loops or memory leaks if circular dependencies exist. Combining toRaw with a WeakSet allows identifying visited raw references without preventing garbage collection of unreferenced nodes.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { toRaw, reactive } from 'vue';export function createGraphNode(val) {const visitedNodes = new WeakSet();function sanitize(node) {const rawNode = toRaw(node);if (typeof rawNode !== 'object' || rawNode === null) return rawNode;if (visitedNodes.has(rawNode)) return '[Circular]';visitedNodes.add(rawNode);return rawNode;}const state = reactive({ value: val, children: [] });return { state, sanitize };}
vue
Breakdown
1
const rawNode = toRaw(node);
Unwraps Vue reactive proxy to obtain the underlying raw object reference for identity checking.
2
if (visitedNodes.has(rawNode)) return '[Circular]';
Uses WeakSet to detect circular references without maintaining strong references that cause GC leaks.