0 day streak
javascript / expert
Snippet

Manual Effect Disposal with effectScope

The effectScope API allows you to group reactive effects (watchers, computed properties) so they can be disposed of all at once. This is essential for managing reactivity in external classes or services where the automatic component-unmount cleanup isn't available.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
import { effectScope, watch, ref } from 'vue';
const scope = effectScope();
const count = ref(0);
scope.run(() => {
watch(count, (val) => console.log(`Count: ${val}`));
});
// Later, to dispose all effects within the scope
scope.stop();
vue
Breakdown
1
const scope = effectScope();
Initializes a new reactive effect scope container.
2
scope.run(() => { ... });
Executes a function where any created reactivity is captured by this scope.
3
scope.stop();
Recursively disposes of all captured effects, preventing memory leaks.