javascript / expert
Snippet
Private Class Fields with WeakRef Caching for Stateful React Subscriptions
In object-oriented state management architectures for React, encapsulating listener registries using ES2022 private class fields ('#') enforces true runtime encapsulation. Combining private fields with WeakRef allows storing heavy payload references without preventing garbage collection if React unmounts subscriber components.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
export class ReactSubscriptionManager {#listeners = new Set();#cacheRef = null;subscribe(listener) {this.#listeners.add(listener);return () => this.#listeners.delete(listener);}setCachedPayload(payload) {this.#cacheRef = new WeakRef(payload);}getCachedPayload() {return this.#cacheRef ? this.#cacheRef.deref() : undefined;}}
react
Breakdown
1
#listeners = new Set();
Declares a private instance field inaccessible outside class methods for strict state privacy.
2
this.#cacheRef = new WeakRef(payload);
Holds a weak reference to state objects allowing garbage collection when unreferenced elsewhere.
3
return this.#cacheRef ? this.#cacheRef.deref() : undefined;
Safely dereferences the target payload object or yields undefined if reclaimed by GC.