0Pricing
Vue Academy · Lesson

onUnmounted and Cleanup Patterns

Clearing intervals, removing event listeners, canceling requests in onUnmounted.

onUnmounted and Cleanup Patterns is a free Vue Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Vue Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Cleaning Up After Yourself

When a component is removed, anything it started — timers, listeners, subscriptions, network requests — keeps running unless you stop it. The onUnmounted hook is where you clean up to prevent memory leaks and bugs.

The onUnmounted Hook

onUnmounted fires after the component has been removed from the DOM. It is the last chance to release resources.

<script setup>
import { onUnmounted } from 'vue'
onUnmounted(() => {
  console.log('component removed')
})
</script>

Pattern: Clearing Intervals

If you start an interval in onMounted, clear it in onUnmounted. Otherwise the callback keeps firing after the component is gone, often crashing on missing state.

<script setup>
import { onMounted, onUnmounted } from 'vue'
let id
onMounted(() => { id = setInterval(tick, 1000) })
onUnmounted(() => clearInterval(id))
</script>

Pattern: Removing Event Listeners

Global listeners on window or document survive component removal. Always pair addEventListener with removeEventListener.

<script setup>
import { onMounted, onUnmounted } from 'vue'
function onResize() {}
onMounted(() => window.addEventListener('resize', onResize))
onUnmounted(() => window.removeEventListener('resize', onResize))
</script>

Pattern: Aborting Fetch Requests

A pending request that resolves after unmount can set state on a dead component. Use an AbortController to cancel it during cleanup.

<script setup>
import { onMounted, onUnmounted } from 'vue'
const controller = new AbortController()
onMounted(() => {
  fetch('/api/data', { signal: controller.signal })
})
onUnmounted(() => controller.abort())
</script>

Pattern: Unsubscribing

Subscriptions to stores, sockets, or event buses must be torn down. Save the unsubscribe function and call it in onUnmounted.

<script setup>
import { onMounted, onUnmounted } from 'vue'
let unsubscribe
onMounted(() => { unsubscribe = store.subscribe(handler) })
onUnmounted(() => unsubscribe && unsubscribe())
</script>

watch Returns a Stop Function

Calling watch returns a function that stops it. Watchers created during setup stop automatically, but watchers created later (for example, inside another callback) should be stopped manually.

<script setup>
import { watch, onUnmounted } from 'vue'
const stop = watch(source, handler)
onUnmounted(() => stop())
</script>

watchEffect Cleanup Callback

Inside watchEffect you receive an onCleanup function to clean up before the next run or on stop. This keeps per-run resources tidy.

watchEffect((onCleanup) => {
  const timer = setTimeout(doWork, 500)
  onCleanup(() => clearTimeout(timer))
})

Why Cleanup Matters

Skipping cleanup leads to memory leaks (resources never freed), duplicate listeners (multiple mounts stack up), and errors (callbacks touching destroyed state). Clean code always tears down what it sets up.

Composables Make It Automatic

Well-written composables register their own cleanup in onUnmounted. That is why VueUse composables like useEventListener remove the listener for you — the cleanup is built in.

Cleanup Checklist

  • setInterval/setTimeout -> clear them.
  • addEventListener -> remove it.
  • fetch -> abort with AbortController.
  • subscriptions -> call unsubscribe.
  • manual watchers -> call the returned stop function.

Quick Check

Test your cleanup knowledge.

Recap

Cleanup essentials:

  • onUnmounted runs after removal — release resources here.
  • Clear intervals/timeouts, remove listeners, abort fetches, unsubscribe.
  • watch returns a stop function to call in onUnmounted when needed.
  • watchEffect provides an onCleanup callback for per-run cleanup.

Frequently asked questions

Is the “onUnmounted and Cleanup Patterns” lesson free?

Yes — the full text of “onUnmounted and Cleanup Patterns” is free to read here on the web, and the Vue Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Vue Academy course, upgrade to CoddyKit PRO.

What will I learn in “onUnmounted and Cleanup Patterns”?

Clearing intervals, removing event listeners, canceling requests in onUnmounted. You practise Vue Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Vue Academy?

No prior experience is required. Vue Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “onUnmounted and Cleanup Patterns” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Vue Academy lesson?

Yes. Every Vue Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Lifecycle Phases Overview
  2. onMounted and onBeforeMount
  3. onUpdated and onBeforeUpdate
  4. onUnmounted and Cleanup Patterns
← Back to Vue Academy