0 day streak
javascript / expert
Snippet

Manual Reactivity Disposal with EffectScope

EffectScope is an advanced API for grouping reactive effects so they can be disposed of together. This is critical for preventing memory leaks in manual logic that exists outside of component lifecycles.

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 is: ${val}`));
});
// Later, dispose of all effects inside the scope at once
scope.stop();
vue
Breakdown
1
const scope = effectScope();
Creates an effect scope object that can capture reactive effects like watchers and computed properties.
2
scope.run(() => { ... });
Executes a function where any created effects are automatically associated with this scope.
3
scope.stop();
Recursively disposes of all effects captured within the scope, cleaning up memory and listeners.