Cleanup with Reactive Effect
Demonstrate how to perform cleanup actions in a reactive effect using the onInvalidate function inside watchEffect.
const { ref, watchEffect } = Vue;
// Assume we have a Vue app where we want to watch a reactive source
const counter = ref(0);
// The watchEffect function is used to automatically run a function when
// the reactive sources it uses change.
watchEffect((onInvalidate) => {
// This is our reactive effect, which runs whenever 'counter' changes
console.log(`The counter is now: ${counter.value}`);
// Suppose we have a subscription that needs to be cleaned up
const intervalId = setInterval(() => {
console.log('Interval tick');
}, 1000);
// onInvalidate can be used to register a cleanup function
// that runs when the watcher is about to re-run or is stopped
onInvalidate(() => {
clearInterval(intervalId); // Cleanup the interval when the effect needs to re-run or the watcher is stopped
console.log('Cleanup interval');
});
});
This piece of code demonstrates how to create a reactive effect with Vue's watchEffect API and how to perform cleanup using the onInvalidate function. It watches a reactive counter variable, setting up an interval that prints to the console. The onInvalidate function is used to provide a cleanup function that clears the interval, ensuring no resources are left hanging when the reactive effect is re-run or the component is destroyed.