Blog>
Snippets

Effect Scope with Scope Management

Provide an example of scope management using effectScope to group effects and show how to destroy them all at once.
// Vue 3's effectScope example to group reactive effects

import { effectScope, ref } from 'vue';

// Create a new effect scope
const scope = effectScope();

// Enter the scope to start collecting effects
scope.run(() => {
  // Define reactive state
  const count = ref(0);

  // Watch the reactive state and log the count
  watch(count, (newValue) => {
    console.log('Count changed:', newValue);
  });

  // Mutate the state to trigger effect
  count.value++;
});

// Later, when we want to destroy all effects in the scope
canDestroy && scope.stop();
This code creates a new effect scope using Vue 3's effectScope. Inside the scope, a reactive state is defined using ref and a watcher is set up to log changes to that state. By increasing the count, the effect is triggered. Later, all effects can be destroyed at once by calling the `stop` method on the scope. The `canDestroy` variable is a placeholder indicating a condition that must be true to stop the scope.
// An example to demonstrate how to stop all effects when a component unmounts

import { onUnmounted } from 'vue';

// Assume we are inside a component setup function
// Previously created effectScope
const scope = effectScope();

onUnmounted(() => {
  // Stop all effects in the scope when the component unmounts
  scope.stop();
});
This code snippet shows how to automatically stop all effects within an effect scope when a Vue component unmounts. We listen for the `onUnmounted` lifecycle hook and call the `stop` method on the effect scope to clean up effects and prevent memory leaks.