Consider this Vue 3 component using the Composition API. What will happen when the component unmounts?
import { ref, onMounted, onUnmounted } from 'vue'; export default { setup() { const count = ref(0); onMounted(() => { const interval = setInterval(() => { count.value++; }, 1000); onUnmounted(() => { clearInterval(interval); }); }); return { count }; } }
Think about when lifecycle hooks run and if nesting affects their execution.
In Vue 3, lifecycle hooks like onUnmounted can be called inside onMounted. The cleanup function registered with onUnmounted will run when the component unmounts, clearing the interval properly.
watchEffect?In Vue 3, watchEffect can return a cleanup function. When exactly is this cleanup function executed?
import { ref, watchEffect } from 'vue'; export default { setup() { const count = ref(0); watchEffect((onCleanup) => { console.log('Effect runs with count:', count.value); onCleanup(() => { console.log('Cleanup for count:', count.value); }); }); return { count }; } }
Think about how watchEffect manages reactive dependencies and cleanup.
The cleanup function in watchEffect runs before the effect re-runs to clean up previous side effects, and also when the component unmounts to avoid memory leaks.
Examine the code below. Why does the cleanup function not execute when the component unmounts?
import { ref, onMounted, onUnmounted } from 'vue'; export default { setup() { const timer = ref(null); onMounted(() => { timer.value = setTimeout(() => { console.log('Timer done'); }, 1000); }); onUnmounted(() => { clearTimeout(timer.value); }); return {}; } }
Check the argument passed to clearTimeout carefully.
The timer is a ref object, so timer itself is an object, not the timer ID. The correct call should be clearTimeout(timer.value) to clear the actual timer.
onMounted hook?Choose the code snippet that correctly registers a cleanup function to run when the component unmounts.
Remember the correct lifecycle hook for cleanup in Vue 3.
In Vue 3, onUnmounted is the correct hook to register cleanup functions. Returning a function from onMounted or using onCleanup or cleanup are not valid Vue 3 APIs.
In Vue 3's Composition API, why should cleanup functions be registered inside the setup() function rather than outside it?
Think about how Vue tracks component lifecycles and reactive scopes.
Cleanup functions must be registered inside setup() so they are linked to the component's lifecycle. This ensures cleanup runs exactly when the component unmounts, preventing memory leaks and stale effects.