Bird
Raised Fist0
Vueframework~10 mins

Effective scope for cleanup in Vue - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Effective scope for cleanup
Component Setup
↓
Create Reactive State
↓
Register Effect or Watch
↓
Effect Runs
↓
Component Unmount
↓
Cleanup Function Runs
↓
Resources Freed
↓
Component Removed or Updated
This flow shows how Vue sets up reactive effects and cleans them up automatically when the component unmounts.
Execution Sample
Vue
import { ref, watchEffect, onUnmounted } from 'vue'

const count = ref(0)
const stop = watchEffect(() => {
  console.log(`Count is: ${count.value}`)
})
onUnmounted(() => stop())
This code sets up a reactive effect that logs count changes and cleans up the watcher when the component unmounts.
Execution Table
StepActionReactive StateEffect StatusCleanup StatusOutput
1Initialize count = 0count=0No effect yetNo cleanup
2Start watchEffectcount=0Effect activeNo cleanupLogs: Count is: 0
3Update count to 1count=1Effect re-runsNo cleanupLogs: Count is: 1
4Component unmount triggers cleanupcount=1Effect stoppedCleanup function called
5Effect stopped, no further logscount=1No effectCleanup done
💡 Cleanup runs when component unmounts, stopping the effect and freeing resources.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
count00111
Effect activefalsetruetruefalsefalse
Cleanup calledfalsefalsefalsetruetrue
Key Moments - 2 Insights
Why does the cleanup function run only when the component unmounts?
Because Vue calls the cleanup registered by onUnmounted only when the component is removed, as shown in step 4 of the execution_table.
What happens if we don't call the cleanup function returned by watchEffect?
Vue automatically stops the effect on component unmount, preventing memory leaks or unwanted side effects. Manual cleanup provides explicit control.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of count after step 3?
A1
B0
Cundefined
Dnull
💡 Hint
Check the 'Reactive State' column at step 3 in the execution_table.
At which step does the cleanup function run?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Cleanup Status' column in the execution_table.
If we remove the onUnmounted cleanup call, what happens to the effect after unmount?
AEffect runs only once
BEffect stops automatically
CEffect keeps running causing potential leaks
DEffect throws an error
💡 Hint
Vue automatically cleans up reactive effects created in setup() on component unmount.
Concept Snapshot
Vue cleanup scope:
- Setup reactive effect with watchEffect
- Effect runs immediately and on dependency changes
- Vue automatically cleans up effects on component unmount
- Manual cleanup: onUnmounted(() => stop())
- Prevents memory leaks and stale effects
Full Transcript
In Vue, when you create reactive effects using watchEffect, the effect runs immediately and whenever its dependencies change. Vue automatically cleans up these effects when the component unmounts. Vue provides onUnmounted to register cleanup functions. The cleanup function returned by watchEffect stops the effect from running further. This process ensures resources are freed and the component behaves correctly. The execution table shows the effect starting, running on state change, and cleaning up on unmount.

Practice

(1/5)
1. In Vue, which lifecycle hook is best to use for cleaning up timers or event listeners when a component is removed?
easy
A. onUpdated
B. onMounted
C. onUnmounted
D. onCreated

Solution

  1. Step 1: Understand Vue lifecycle hooks

    onMounted runs when the component appears, onUnmounted runs when it disappears.
  2. Step 2: Identify cleanup timing

    Cleanup like stopping timers or removing listeners should happen when the component is removed, so onUnmounted is the right hook.
  3. Final Answer:

    onUnmounted -> Option C
  4. Quick Check:

    Cleanup runs on unmount = C [OK]
Hint: Cleanup always goes in onUnmounted hook [OK]
Common Mistakes:
  • Using onMounted for cleanup
  • Confusing onUpdated with cleanup
  • Trying to cleanup in onCreated
2. Which of the following is the correct syntax to register a cleanup function in Vue's setup() using the onUnmounted hook?
easy
A. onUnmounted(() => { clearInterval(timer) })
B. onUnmounted = () => { clearInterval(timer) }
C. onUnmounted.clear(() => { clearInterval(timer) })
D. onUnmounted.clearInterval(timer)

Solution

  1. Step 1: Recall Vue hook syntax

    Vue lifecycle hooks like onUnmounted are functions that take a callback to run on that event.
  2. Step 2: Match correct syntax

    The correct way is calling onUnmounted with a function: onUnmounted(() => { ... }). Other options misuse assignment or methods.
  3. Final Answer:

    onUnmounted(() => { clearInterval(timer) }) -> Option A
  4. Quick Check:

    Hook usage = function call with callback [OK]
Hint: Hooks are called with a function, not assigned [OK]
Common Mistakes:
  • Assigning instead of calling onUnmounted
  • Using nonexistent methods on onUnmounted
  • Missing arrow function wrapper
3. What will be the console output when this Vue component unmounts?
setup() {
  const timer = setInterval(() => console.log('tick'), 1000)
  onUnmounted(() => clearInterval(timer))
}
medium
A. Logs 'tick' only once when component unmounts
B. Logs 'tick' every second until component unmounts, then stops
C. No logs appear at all
D. Throws an error on unmount

Solution

  1. Step 1: Understand setInterval behavior

    setInterval logs 'tick' every 1000ms continuously until cleared.
  2. Step 2: Analyze cleanup with onUnmounted

    When the component unmounts, clearInterval(timer) stops the interval, so logging stops after unmount.
  3. Final Answer:

    Logs 'tick' every second until component unmounts, then stops -> Option B
  4. Quick Check:

    Interval runs until cleared on unmount [OK]
Hint: Intervals run until cleared in onUnmounted [OK]
Common Mistakes:
  • Thinking logs stop immediately without unmount
  • Expecting logs only once on unmount
  • Assuming error on clearInterval
4. Identify the problem in this Vue setup function and how to fix it:
setup() {
  const timer = setInterval(() => console.log('tick'), 1000)
  onMounted(() => clearInterval(timer))
}
medium
A. Cleanup runs too early; should use onUnmounted instead
B. Timer is never created; setInterval is missing
C. clearInterval is called without timer variable
D. No problem; code works correctly

Solution

  1. Step 1: Check when cleanup runs

    Using onMounted to clear interval means it stops immediately after mounting, so no ticks happen.
  2. Step 2: Correct cleanup timing

    Cleanup should happen when component unmounts, so onUnmounted is the correct hook to clear the timer.
  3. Final Answer:

    Cleanup runs too early; should use onUnmounted instead -> Option A
  4. Quick Check:

    Cleanup must be on unmount, not mount [OK]
Hint: Cleanup belongs in onUnmounted, not onMounted [OK]
Common Mistakes:
  • Clearing timer on mount instead of unmount
  • Assuming onMounted is for cleanup
  • Ignoring lifecycle hook purpose
5. You have a Vue component that subscribes to a WebSocket in 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?
}
hard
A. Call socket.close() immediately after creating socket
B. No cleanup needed for WebSocket in Vue
C. Use onMounted(() => socket.close()) to close socket on mount
D. Use onUnmounted(() => socket.close()) inside setup

Solution

  1. Step 1: Understand WebSocket lifecycle

    WebSocket stays open until closed; closing it too early stops messages.
  2. Step 2: Place cleanup in onUnmounted

    To avoid leaks, close the socket when component unmounts using onUnmounted(() => socket.close()).
  3. Final Answer:

    Use onUnmounted(() => socket.close()) inside setup -> Option D
  4. Quick Check:

    Cleanup subscriptions on unmount with onUnmounted [OK]
Hint: Close subscriptions in onUnmounted hook [OK]
Common Mistakes:
  • Closing socket immediately after creation
  • Closing socket on mount instead of unmount
  • Skipping cleanup causing memory leaks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard