Cleaning up resources like timers or event listeners helps keep your app fast and bug-free. It stops things from running when they are no longer needed.
Effective scope for cleanup in Vue
<script setup> import { onUnmounted } from 'vue' const timer = setInterval(() => { console.log('Tick') }, 1000) onUnmounted(() => { clearInterval(timer) }) </script>
onUnmounted runs cleanup code when the component is removed from the page.
Always pair setup code (like timers) with cleanup code to avoid leftover effects.
<script setup> import { onUnmounted } from 'vue' const listener = () => console.log('Clicked') window.addEventListener('click', listener) onUnmounted(() => { window.removeEventListener('click', listener) }) </script>
<script setup> import { ref, onUnmounted } from 'vue' const count = ref(0) const interval = setInterval(() => { count.value++ }, 1000) onUnmounted(() => { clearInterval(interval) }) </script>
This component shows seconds passed. It starts a timer when created and clears it when removed to stop counting.
<template>
<div>
<p>Seconds passed: {{ seconds }}</p>
</div>
</template>
<script setup>
import { ref, onUnmounted } from 'vue'
const seconds = ref(0)
const timer = setInterval(() => {
seconds.value++
}, 1000)
onUnmounted(() => {
clearInterval(timer)
console.log('Timer cleared on unmount')
})
</script>Always use onUnmounted to clean up side effects in Vue components.
Forgetting to clean up can cause bugs or slow down your app over time.
Cleanup functions run automatically when the component is removed from the page.
Use onUnmounted to run cleanup code in Vue components.
Cleanup stops timers, listeners, or subscriptions to keep your app healthy.
Always match setup code with cleanup to avoid memory leaks.
Practice
Solution
Step 1: Understand Vue lifecycle hooks
onMountedruns when the component appears,onUnmountedruns when it disappears.Step 2: Identify cleanup timing
Cleanup like stopping timers or removing listeners should happen when the component is removed, soonUnmountedis the right hook.Final Answer:
onUnmounted-> Option CQuick Check:
Cleanup runs on unmount = C [OK]
- Using onMounted for cleanup
- Confusing onUpdated with cleanup
- Trying to cleanup in onCreated
setup() using the onUnmounted hook?Solution
Step 1: Recall Vue hook syntax
Vue lifecycle hooks likeonUnmountedare functions that take a callback to run on that event.Step 2: Match correct syntax
The correct way is callingonUnmountedwith a function:onUnmounted(() => { ... }). Other options misuse assignment or methods.Final Answer:
onUnmounted(() => { clearInterval(timer) }) -> Option AQuick Check:
Hook usage = function call with callback [OK]
- Assigning instead of calling onUnmounted
- Using nonexistent methods on onUnmounted
- Missing arrow function wrapper
setup() {
const timer = setInterval(() => console.log('tick'), 1000)
onUnmounted(() => clearInterval(timer))
}Solution
Step 1: Understand setInterval behavior
setInterval logs 'tick' every 1000ms continuously until cleared.Step 2: Analyze cleanup with onUnmounted
When the component unmounts,clearInterval(timer)stops the interval, so logging stops after unmount.Final Answer:
Logs 'tick' every second until component unmounts, then stops -> Option BQuick Check:
Interval runs until cleared on unmount [OK]
- Thinking logs stop immediately without unmount
- Expecting logs only once on unmount
- Assuming error on clearInterval
setup() {
const timer = setInterval(() => console.log('tick'), 1000)
onMounted(() => clearInterval(timer))
}Solution
Step 1: Check when cleanup runs
UsingonMountedto clear interval means it stops immediately after mounting, so no ticks happen.Step 2: Correct cleanup timing
Cleanup should happen when component unmounts, soonUnmountedis the correct hook to clear the timer.Final Answer:
Cleanup runs too early; should use onUnmounted instead -> Option AQuick Check:
Cleanup must be on unmount, not mount [OK]
- Clearing timer on mount instead of unmount
- Assuming onMounted is for cleanup
- Ignoring lifecycle hook purpose
setup(). Which pattern correctly ensures the subscription is cleaned up only when the component unmounts?setup() {
const socket = new WebSocket('wss://example.com')
socket.onmessage = (event) => console.log(event.data)
// What cleanup code and where?
}Solution
Step 1: Understand WebSocket lifecycle
WebSocket stays open until closed; closing it too early stops messages.Step 2: Place cleanup in onUnmounted
To avoid leaks, close the socket when component unmounts usingonUnmounted(() => socket.close()).Final Answer:
Use onUnmounted(() => socket.close()) inside setup -> Option DQuick Check:
Cleanup subscriptions on unmount with onUnmounted [OK]
- Closing socket immediately after creation
- Closing socket on mount instead of unmount
- Skipping cleanup causing memory leaks
Ready to prove it?
Pass the test and this pattern moves unknown
