Preventing Memory Leaks with Vue 3.5 useTemplateRef and onWatcherCleanup

Hello, this is Lovefield.

As a Vue application grows, extracting reusable logic into composables becomes second nature. Along the way, two recurring bugs tend to creep into real-world codebases.

First, referencing DOM elements with ref(null) often leads to naming collisions with reactive state and repetitive manual TypeScript annotations. Second, async requests or event listeners triggered inside watch frequently cause race conditions and memory leaks when cleanup isn't handled consistently.

Vue 3.5 addresses both pain points natively with useTemplateRef() and onWatcherCleanup(). In this post, we will explore how these APIs work and how to combine them into clean, leak-free composables.

Safer, Explicit DOM References with useTemplateRef

Previously in Vue 3, accessing a template DOM node required matching a <input ref="searchInput" /> attribute with a variable of the exact same name: const searchInput = ref<HTMLInputElement | null>(null).

In larger components, it quickly becomes hard to tell which ref holds reactive data and which one points to a DOM element—not to mention the boilerplate of manually typing every element.

Vue 3.5's useTemplateRef() cleanly separates template references from reactive state:

Vue

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<script setup lang="ts">
import { onMounted, useTemplateRef } from 'vue';

// Explicitly bound to ref="search-input" (Volar infers HTMLInputElement automatically)
const inputEl = useTemplateRef('search-input');

onMounted(() => {
  inputEl.value?.focus();
});
</script>

<template>
  <input ref="search-input" type="text" placeholder="Search..." />
</template>

The practical advantages stand out right away:

  • Decoupled naming: Use kebab-case keys like search-input in your template while keeping descriptive variable names like inputEl in <script setup>.

  • Automatic type inference: With modern Volar (Vue Language Tools), the return type is automatically inferred as Readonly<ShallowRef<HTMLInputElement | null>> without manual generics.

  • Cleaner composables: Passing a template ref key string into a composable is far simpler than passing reactive ref objects around.

Stopping Race Conditions and Leaks with onWatcherCleanup

Consider a search input that triggers an API call inside watch whenever the user types. If an earlier, slower network request resolves after a newer one, stale data overwrites the latest results—a classic race condition.

While watch previously offered an onCleanup callback parameter, threading that callback down into nested helper functions or composables was awkward.

With onWatcherCleanup() in Vue 3.5, you can register a cleanup handler from anywhere synchronously inside a watch or watchEffect.

Combining onWatcherCleanup with AbortController

TypeScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

import { ref, watch, onWatcherCleanup } from 'vue';

export function useSearchQuery() {
  const keyword = ref('');
  const results = ref<string[]>([]);
  const isLoading = ref(false);

  watch(keyword, async (newKeyword) => {
    if (!newKeyword.trim()) {
      results.value = [];
      return;
    }

    const controller = new AbortController();

    // Abort the previous request on re-run or component unmount
    onWatcherCleanup(() => {
      controller.abort();
    });

    isLoading.value = true;
    try {
      const response = await fetch(`/api/search?q=${encodeURIComponent(newKeyword)}`, {
        signal: controller.signal,
      });
      results.value = await response.json();
    } catch (error) {
      if (error instanceof DOMException && error.name === 'AbortError') {
        return; // Ignore intentional cancellations
      }
      console.error('Search request failed:', error);
    } finally {
      if (!controller.signal.aborted) {
        isLoading.value = false;
      }
    }
  });

  return { keyword, results, isLoading };
}

> Important: Always call onWatcherCleanup() synchronously before any await statement inside your watcher callback. After an await, the active watcher context is lost and Vue cannot bind the cleanup function.

Combining Both APIs in a Practical Composable

Pairing useTemplateRef with onWatcherCleanup makes it effortless to build DOM event composables that automatically clean up listeners whenever an element toggles via v-if or the component unmounts:

TypeScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

// composables/useElementEvent.ts
import { useTemplateRef, watchEffect, onWatcherCleanup } from 'vue';

export function useElementEvent<K extends keyof HTMLElementEventMap>(
  refKey: string,
  event: K,
  handler: (e: HTMLElementEventMap[K]) => void,
) {
  const targetEl = useTemplateRef<HTMLElement>(refKey);

  watchEffect(() => {
    const el = targetEl.value;
    if (!el) return;

    el.addEventListener(event, handler);

    // Automatically remove the listener when the element disappears or unmounts
    onWatcherCleanup(() => {
      el.removeEventListener(event, handler);
    });
  });
}

Inside any component, binding a safe, self-cleaning DOM listener takes just one line—no manual onMounted or onUnmounted hooks required:

Vue

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<script setup lang="ts">
import { useElementEvent } from '~/composables/useElementEvent';

useElementEvent('scroll-box', 'scroll', (e) => {
  const target = e.currentTarget as HTMLElement;
  console.log('Current scroll position:', target.scrollTop);
});
</script>

<template>
  <div ref="scroll-box" class="scroll-container">
    <!-- Scrollable content -->
  </div>
</template>

Summary

Memory leaks and async race conditions rarely show up during quick local testing—they surface in production when users keep tabs open or interact rapidly with the UI.

By adopting Vue 3.5's useTemplateRef() for clear, type-safe DOM references and onWatcherCleanup() for deterministic async and listener lifecycles, you can cut down boilerplate while making your composables significantly more resilient.

This article was generated by AI.

Lovefield

Web Front-End developer

하고싶은게 많고, 나만의 서비스를 만들고 싶은 변태스러운 개발자입니다.

Reducing Framework Dependency with Modern CSS: Practical View Transitions API and Container Queries

Move beyond heavy JavaScript animation libraries and rigid viewport media queries. Learn how to build lightweight, reusable UIs in Vue and Nuxt using native View Transitions API and CSS Container Queries (@container).

CSS

v5.0