Describe a practical use case for a `WeakSet` where a regular `Set` would be inappropriate. Explain the specific problem that `WeakSet` solves in this scenario.

React JS interview question for Advanced practice.

Answer

A practical use case for a WeakSet is tracking which components in a UI framework have been 'activated' or 'selected' by a user. For example, a user might click on several complex components to select them for a batch operation. javascript const selectedComponents = new WeakSet(); class SelectableComponent { constructor() { this.element = document.createElement('div'); this.element.onclick = () = { this.element.classList.toggle('selected'); if (selectedComponents.has(this)) { selectedComponents.delete(this); } else { selectedComponents.add(this); } }; } // ... methods to render and destroy the component } The Problem Solved by WeakSet: In this scenario, components can be created and destroyed dynamically. If we used a regular Set to track the selected components, it would create a strong reference to each component instance added to it. When a component is destroyed and removed from the UI, the Set would still hold a reference to it. This would prevent the component object from being garbage collected, leading to a memory leak. A WeakSet solves this problem perfectly. It holds a weak reference to the component instances. When a component is destroyed and all other references to it are gone, the garbage collector can reclaim its memory, and the WeakSet will automatically remove its entry. This allows us to track 'live' selected objects without having to manually implement a cleanup mechanism, thus preventing memory leaks.

Explanation

Frameworks and libraries can use WeakSets to track 'live' objects (like active UI components) without needing a manual cleanup process when those objects are destroyed.

Related Questions