Blog>
Snippets

Manual Reactive Effect Teardown

Illustrate how to manually stop a reactive effect from running by calling the stop function returned by watchEffect.
// Importing the reactive and watchEffect utilities from Vue or a similar library
import { reactive, watchEffect } from 'vue';

// Define a reactive object
const state = reactive({
    count: 0
});

// Defining the watchEffect which will be automatically called when the reactive state changes
const stop = watchEffect(() => {
    console.log(`The count is: ${state.count}`);
});

// Changing the state to trigger the effect
state.count++;

// After some condition or event, we want to stop the effect from running further
setTimeout(() => {
    // Call the stop function to teardown the manual reactive effect
    stop();
    console.log('Effect has been stopped.');
}, 3000);
This code snippet showcases how to create a reactive state using Vue's reactive function. A watchEffect is initialized to reactively log changes to the 'count' property. The stop function returned from watchEffect is then used to manually teardown the effect after 3 seconds. The reactive effect will stop running any further even if the state changes thereafter.